Convert sting to datetime

How to convert in MS SQL server 2005 from string to Datetime datatype

SELECT
[customer_key] ,
[company_code],
[distributor_code] ,
[dist_center],
[cust_code_ref] ,
[customer_name],
[customer_code],
[status],
[changedby] ,
CASE WHEN [status_date] ='0001-01-01' THEN CONVERT(DATETIME,'0001-01-01',111) ELSE CONVERT(DATETIME,[status_date],111) END AS [status_date],
[status_time]
FROM [stagedw].[dbo].[customer_cross_reference_src] a

Giving error:

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

July 29th, 2015 7:25am

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.


It's because the type "datetime" supports only years in the range 1753 - 9999, but not 0001; here you have to use datetime2 or date instead
Free Windows Admin Tool Kit Click here and download it now
July 29th, 2015 7:34am

But I am using MS SQL Server 2005 which does not have Datetime2 or date.

Is there any other way ?

Thanks for ur comment.

July 29th, 2015 7:40am

Can you change/replace 0001 to 1900 in CASE expression (THEN)?
Free Windows Admin Tool Kit Click here and download it now
July 29th, 2015 7:45am

Or Change it to NULL value, if the column in the table is nullable.
July 29th, 2015 7:53am

"Is there any other way ?"

You can't change the range for the datetime data type. Either convert it to datetime and keep the values within the allowed range, or use some other type (like varchar). NULL, is of course always an option (for all types), where ppropriate.

Free Windows Admin Tool Kit Click here and download it now
July 30th, 2015 5:16pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics