views:

43

answers:

3

i want to normalize date fields from an old badly designed db dump. i now need to update every row, where the datefield only contains the year.

update table set date = '01.01.' + date
where date like '____' and isnumeric(date) = 1 and date >= 1950

but this will not work, because sql does not do short circuit evaluation of boolean expressions. thus i get an error "error converting nvarchar '01.07.1989' to int"

is there a way to work around this? the column also contains strings with a length of 4, which are not numbers (????, 5/96, 70/8, etc.) the table only has 60000 rows

+1  A: 

How about just enclosing 1950 in single quotes?

I ran a quick test:

DECLARE @Table TABLE (Date NVARCHAR(20))
INSERT @Table 
SELECT '2010' 
UNION ALL 
SELECT '2009' 
UNION ALL 
SELECT '01.07.1989' 
UNION ALL 
SELECT '1951'
UNION ALL
SELECT '1940'
UNION ALL
SELECT 'Some Text'

UPDATE @Table
SET Date = '01.01.' + date
WHERE date LIKE '____' AND ISNUMERIC(date) = 1 AND date>='1950'

SELECT * FROM @Table
AdaTheDev
+1  A: 

You could always do a subquery

update table set date = '01.01.' + date
where id in(

   select id from table
   where date like '____' and isnumeric(date)

)
and convert(int, date) >= 1950
David Hedlund
A: 

Maybe add a new field to store actual datetime Value:

alter table [Table] add [RealDate] datetime;
update [Table] set [RealDate] = cast([Date] as datetime) where isdate([Date]) = 1
My Other Me
i need to parse as many dates as possible from the old data, then i do it this way already
knittl