Skip to content
Advertisement

Cast/Convert nvarchar to datetime

i have table:

Table have huge amount these data. Column timestamp is data type “nvarchar”. And i need to sort datas by date or use in clauses WHERE for constraint by date, so i need to convert “timestamp” to datetime. But I can’t. I tried convert and cast but still failed.

Any advice?

Thx.

Advertisement

Answer

Fix your design, and change the column to a date and time data type. Considering your data is accurate to 1 second, a datetime2(0) seems appropriate here. First we need to change the “format” of the nvarchar value to an ISO format. We’re going to use the ISO8601 format (yyyy-mm-ddThh:mi:ss.mmm) as it’s unambiguous:

Now you can ALTER the table and change the data type to a datetime2(0):

I also recommend using a different name than timestamp for your column. timestamp is a deprecated synonym for rowversion, so it’s use can make it quite confusing; especially as rowversion is not a date and time value but a binary value and cannot be converted to a date and time data type.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement