I made the mistake of using varchar to store my data that represents date/time. Now I'm trying to convert my column of text data, stored as a varchar, like so:
2020-11-25T14:22:41.3539327Z
Into a column that stores a datetime datatype.
I made the mistake of using varchar to store my data that represents date/time. Now I'm trying to convert my column of text data, stored as a varchar, like so:
2020-11-25T14:22:41.3539327Z
Into a column that stores a datetime datatype.
Provided that all your data is in the format yyyy-MM-ddThh:mm:ss.nnnnnnn
then you can just change the data type of the column:
ALTER TABLE dbo.YourTABLE ALTER COLUMN YourColumn datetime2(7);
If you need the timezone in there, then use datetimeoffset(7)
instead.
-- to fix it you can use convert, below uses GetDate for examaple
SELECT convert(varchar, getdate(), 120)
depending on what precision you need you can use the link below to find it and change the 120 to whatever number you need for that precision.
https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
To fix your table you should follow these steps:
Code to do the steps I outlined above
ALTER TABLE dbo.TableName ADD NewDateTimeCOL DATETIME
-- NOTE if your table is LARGE you will not want to do a direct update like this but do looping for performace purposes
UPDATE dbo.TableName
SET NewDateTimeCOL = convert(varchar, OldDateTimeCOL, 120)
ALTER TABLE dbo.TableName DROP COLUMN OldDateTimeCOL