1

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

2
  • You can also use Datefromparts to form a date. Nov 3, 2016 at 6:18
  • year, but if i have some invalid date-part then it will not handle that error. Nov 3, 2016 at 6:35

6 Answers 6

2
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.

0
1

You can as the below:

UPDATE Employees 
SET createdate = CAST(CAST(year AS VARCHAR(4)) + '.' + CAST(month AS VARCHAR(2)) + '.' + CAST(day AS VARCHAR(2)) AS DATETIME) 
0
1

You can use DATEFROMPARTS very simple to form date

UPDATE Employees SET CreateDate =DATEFROMPARTS ( year, month, day ) 
0

Try this, it's update for all rows :

UPDATE Employees SET CreateDate = [day] +'/'+ [Month] +'/'+ [year]
0
0
   1)...UPDATE Employees 
    set createdate =
           CAST(
              CAST(year AS VARCHAR(4)) +
              RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
              RIGHT('0' + CAST(day AS VARCHAR(2)), 2) 
           AS DATETIME)


    2)...SELECT
        DATEADD(year, [year]-1900, DATEADD(month, [month]-1, DATEADD(day, [day]-1, 0)))
    FROM
        dbo.Table
0
  UPDATE emp SET CreateDate =( SELECT CONVERT(DATE,CAST([Year] AS VARCHAR(4))+'-'+
                CAST([Month] AS VARCHAR(2))+'-'+
                CAST([Day] AS VARCHAR(2))))

img1

or you can also use this code:

 UPDATE empl SET CreateDate =( SELECT CONVERT(varchar(10),
                CAST([Month] AS VARCHAR(2))+'-'+
                CAST([Day] AS VARCHAR(2))+'-'+CAST([Year] AS VARCHAR(4)),101))

img2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.