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?
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With