Neha Thakur Neha Thakur - 1 month ago 6
SQL Question

Update a column with records from current row in SQL Server

I have an existing SQL Server table

Employees
with 3 columns
month
,
year
and
day
as date parts.

Now I have added a new column
createdate
where I want to insert date as a combination of all 3 columns from the current row.

enter image description here

Answer
UPDATE Employees 
SET createdate = TRY_PARSE(CAST([year] AS VARCHAR(4)) + '/' + CAST([month] AS VARCHAR(2)) + '/' + CAST([day] AS VARCHAR(2)) AS DATETIME) 

If you have invalid data in Month Or Year Or Day Colunm, then above query will update with NULL Value.

NOTE: Try_Parse will work from Sql Server Version 2012 onwards.

Comments