简体   繁体   中英

SQL Server ISDATE before conversion returns error “Conversion failed when converting date and/or time from character string”

I have been given a task of converting dates on a field that is define as Varchar(50) . As expected the dates inside the column were a bit out of the normal formats like this DECEMBER 11, 2011

I have used ISDATE(datefield) but it says

Conversion failed when converting date and/or time from character string

My second option was to update the column using this statement

UPDATE dbo.tbl_arrest_information
SET date_arrested = CASE 
                      WHEN ISDATE(date_arrested) > 0 
                         THEN CONVERT(datetime,  date_arrested) 
                         ELSE '01/01/1901' 
                    END 

I use '01/01/1901' because it doesn't accept null values but it returns an error stating that

String or binary data would be truncated

I am well aware that the date field has a length of 50 so i am at lost why it is happening.

Any advise would be helpful.

Thank you

I'm going to guess that your date_arrested might be a smalldatetime field which will throw errors that ISDATE() will not find because it assumes you are checking for a datetime field. You may have to do something like this:

UPDATE dbo.tbl_arrest_information
SET date_arrested = 
    CASE WHEN ISDATE(date_arrested) > 0 
        THEN CASE WHEN date_arrested BETWEEN '1900-01-01' AND '2079-06-05' THEN CONVERT(datetime, date_arrested) ELSE '01/01/1901' END
        ELSE '01/01/1901' END

You Should Use Correct LANGUAGE And DATEFORMAT With ISDATE()

SET LANGUAGE us_english;  
SET DATEFORMAT mdy;  
SELECT ISDATE('04/15/2008'); --Returns 1.    

Returns 1

SET LANGUAGE us_english;  
SET DATEFORMAT myd;  
SELECT ISDATE('15/04/2008'); --Returns 0.  

Also USE CONVERT ( 1, 2 ,3 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM