How to convert nvarchar column to datetime in SQL Server?


Hello, I am using nvarchar column to store datetime as string, but I would like to convert this column from nvarchar into datetime in sql server. How can I do it.

Current time format is '2019-01-29 14:55:50'


Asked by:- neena
0
: 332 At:- 4/8/2022 12:47:20 PM
SQL Datetime







2 Answers
profileImage Answered by:- vikas_jk

Suppose you have column name 'dattime' in 'newTable', then you can try below code to alter column table and update all string nvarchar date into datetime

alter table newTable alter column dattime datetime null;

if this doesn't work, you can also try this

UPDATE newTable
SET dattime = CONVERT(NVARCHAR(50),CONVERT(SMALLDATETIME, dattime,105))
ALTER TABLE newTable
ALTER COLUMN dattime SMALLDATETIME

// where dattime is column name and newTable is table name

Thanks

1
At:- 4/8/2022 4:13:40 PM
ok, this looks good using alter command to change column type, and convert nvarchar to datetime. 0
By : neena - at :- 4/10/2022 11:59:57 AM


profileImage Answered by:- pika

It depends on your current column datetime saved values also

DECLARE @ndate nvarchar(32) = N'15/03/2010'
SELECT CONVERT(datetime, @ndate, 103)
/**** 103 is datetime format for above example  ***/

Hope it helps.

0
At:- 6/3/2022 7:34:12 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use