views:

232

answers:

2

I'm using SQL server 2008.

I have 2 Tables: Table 1 and Table 2.

Table 1 has 1 column called: OldDate which is nvarchar(255), null
Table 2 has 1 column called: NewDate which is datetime, not null

Example data in Table 1:

26/07/03
NULL
NULL
23/07/2003
7/26/2003
NULL
28/07/03

When i try CAST(OldDate as datetime)

I get this error:

Arithmetic overflow error converting expression to data type datetime.

I need to insert OldDate into NewDate with no errors. I can't skip some rows.

+1  A: 

try using

CONVERT(datetime,OldDate ,103)

the "103" tells the converter that the format is dd/mm/yyyy

EDIT

here is a good like with many examples: http://www.sqlusa.com/bestpractices/datetimeconversion/

You seem to have m/d/y as well as d/m/y data, this is about the best you can do:

DECLARE @Table1 table (PK int, OldDate nvarchar(255) null)
DECLARE @Table2 table (PK int, NewDate datetime not null)
INSERT @Table1 VALUES (1,'26/07/03')
INSERT @Table1 VALUES (2,null)
INSERT @Table1 VALUES (3,null)
INSERT @Table1 VALUES (4,'23/07/2003')
INSERT @Table1 VALUES (5,'7/26/2003')
INSERT @Table1 VALUES (6,null)
INSERT @Table1 VALUES (7,'28/07/03')

SET DATEFORMAT dmy

INSERT INTO @Table2
        (PK, NewDate)
    SELECT
        PK,
        CASE 
            WHEN ISDATE(OldDate)=1 THEN OldDate
            ELSE '1/1/1900'
        END
        FROM @Table1

SET DATEFORMAT mdy

UPDATE t2
    SET NewDate=OldDate
    FROM @Table2           t2
        INNER JOIN @Table1 t1 ON t2.PK=t1.PK
    WHERE t2.NewDate='1/1/1900' AND ISDATE(OldDate)=1 

SELECT * FROM @Table2

OUTPUT:

PK          NewDate
----------- -----------------------
1           2003-07-26 00:00:00.000
2           1900-01-01 00:00:00.000
3           1900-01-01 00:00:00.000
4           2003-07-23 00:00:00.000
5           2003-07-26 00:00:00.000
6           1900-01-01 00:00:00.000
7           2003-07-28 00:00:00.000

(7 row(s) affected)

I used '1/1/1900' because you have NewDate as NOT NULL.

KM
+1  A: 

It seems you have incorrect data (or a typo).

Some of dates are in British/French standard dd/mm/yyyy(see code 103) and some in USA standard mm/dd/yyyy(code 101).

For the first case you could try CONVERT(datetime, [OldDate], 103),

for the second CONVERT(datetime, [OldDate], 101)

Alex
You may also have data like '' or 30 Feb 2010 or ASAP which are also not valid dates and will need cleaning up. Use the isdate function to find those which are not convertable to date. Also never store a date in a varchar field again!
HLGEM