简体   繁体   中英

SQL Server : convert nvarchar to date

How to convert a string column of datatype nvarchar which looks like DD.MM.YYYY to Date type.

I need the simplest Date type (no need for clock time) so I can treat this column as a date.

Thanks!

Edit: I tried what all recommended but it doesn't work

UPDATE [test3]
SET [column3] = CONVERT(NVARCHAR(50), CONVERT(SMALLDATETIME, [column2], 105))

ALTER TABLE [test3]
ALTER COLUMN [column3] SMALLDATETIME

Error:

The conversion of a nvarchar data type to a smalldatetime data type resulted in an out-of-range value.

If you want to convert to dd.mm.yyyy then you can use like below:

select convert(varchar, getdate(), 104)

but in your case you can just convert nvarchar to date as below:

select convert(date, yourdate)

Based on your edits and what you said you wanted, you appear to be doing things a bit out of order and also, I'm not sure why you used SMALLDATETIME when you just wanted DATE, but OK.

I'm assuming your table has [column2] of type VARCHAR with data that looks like DD.MM.YYYY that you wish to treat as a date rather than string.

First, create a column to hold date information:

ALTER TABLE [test3] ADD [column3] DATE

Then you can populate the new column by converting your string data:

UPDATE [test3] SET [column3] = CONVERT(DATE, [column2], 104)

Also, the format absolutely matters because in the US '03.12.2019' will be converted to March 12 rather than December 3. You can make a real mess if you assume your server's locale settings are correct.

If there's a problem with converting the data in your column?
Then first discover and correct the data that's wrong, or in an unexpected format.

To find them, you could make use of TRY_CONVERT Which does the same as a normal CONVERT .
But instead of throwing errors, a TRY_CONVERT will simply output NULL if the conversion fails.

SELECT TOP 1000 [column2], [column3]
FROM [test3]
WHERE TRY_CONVERT(DATE, [column2], 104) IS NULL
  AND [column2] IS NOT NULL;

Once you found the troublemakers in your data, and corrected them?
Then the update should work.

UPDATE [test3]
SET [column3] = CONVERT(VARCHAR(10), CONVERT(DATE, [column2], 104), 23);

After that the type of column3 can be changed.

ALTER TABLE [test3]
  ALTER COLUMN [column3] DATE;

Or first set all the column3 to NULL, then do the type change, then update from column2.

UPDATE [test3]
SET [column3] = NULL;
WHERE [column3] IS NOT NULL;

ALTER TABLE [test3]
  ALTER COLUMN [column3] DATE;

UPDATE [test3]
SET [column3] = CONVERT(DATE, [column2], 104);
WHERE [column2] IS NOT NULL;

If you do this:

select convert (date, '2021-12-30', 23) as datum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM