Convert an int to date in SQL Server

Year(int)  Month(int)   ProductName     Date(DateTime)
   2013         11        ACB          
   2013         11        CDE

I am trying to update the Date values in the above table.

This query doesn't work.

Is there a way I can convert int to datetime ?

UPDATE t
SET t.[Date] = convert(date, convert(int, 
                       t.[Year]) + '-' + convert(int, t.[Month]) + '-01')
FROM Table t

Answers


You are trying to add integers and strings. This isn't Visual Basic 6.0; you need to be more explicit with your data type conversions, especially when trying to build strings out of numeric types.

Of course, there are easier and more efficient ways to do this than to bother with any clunky conversions to strings anyway:

UPDATE dbo.Table
  SET [Date] = DATEADD(MONTH, [Month]-1, DATEADD(YEAR, [Year]-1900, 0));

In SQL Server 2012 (not sure why you tagged 3 different versions):

UPDATE dbo.Table
  SET [Date] = DATEFROMPARTS([Year],[Month],1);

No reason in either case to use FROM...


Need Your Help

How to measure the amount of time an animation took place using JavaScript

javascript jquery css animation cordova

Let me explain the problem. I'm creating a phonegap application and I have some css animations running. The animation in question is a hand moving onto the screen and when it reaches 300px down the

do sum filtered by year

excel excel-formula

Hi want to create some report using data what I have. Below is what I have.