Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Convert varchar date column to date type

Tags:

date

tsql

I have the following column date in a SQL Server database.

The datatype is currently varchar, and the dates are stored in the following format: 2010-04-24

I'm running the following command:

ALTER TABLE games ALTER COLUMN date date

But I get the following error:

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

What am I doing wrong?

like image 483
kylex Avatar asked Apr 28 '11 15:04

kylex


People also ask

How can convert varchar column to datetime in SQL Server?

UPDATE TABLE MyTable SET NewCol=CONVERT(datetime,RIGHT(@Date,4)+LEFT(@Date,2)+SUBSTRING(@Date,3,2)) //replace the last part for the code that you use to convert from varchar to date.

How do you fix the conversion of a varchar data type to a datetime data type resulted in an out of range value?

Answer: The error is due to an invalid date format being saved to the custom_rmh_rooms_history SQL table. To resolve this issue, the Windows Regional settings need to be modified and the Short Date format needs to be in MM/dd/yyyy format.


1 Answers

There might be a few dates that don't work. Which version of SQL Server are you using? 2008 I presume, if you have a DATE datatype - right?

My suggestion would be:

1) Create a new column of type DATE

ALTER TABLE dbo.Games
   ADD NewDate DATE

2) Run an update script on your table and see which entries might not convert into DATE

UPDATE dbo.Games
SET NewDate = CAST([date] AS DATE)
WHERE ISDATE([date]) = 1

The check for ISDATE() = 1 should filter out those entries that cannot be converted to a DATE datatype.

Once all your entries have been successfully converted, you could always drop the old [date] column and rename the new column back to [date] - but using a reserved word like DATE for a column name isn't really smart - I'd try to use something more speaking, something more expressive (relating to the problem domain you're in).

like image 160
marc_s Avatar answered Oct 07 '22 02:10

marc_s