Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime [duplicate]

Possible Duplicate:
Create a date with T-SQL

I've a data table that stores each year, month and day value as ints:

year | month | day 2009 |   1   |  1  2008 |  12   |  2 2007 |   5   |  5 

I need to convert it to datetime value, because I need to use it in a datetime between operation. How could I do this?

like image 206
balint Avatar asked Dec 17 '09 19:12

balint


People also ask

How can create date from day month and year in SQL?

SQL Server DATEFROMPARTS() Function The DATEFROMPARTS() function returns a date from the specified parts (year, month, and day values).

Can we convert integer to date in SQL?

The method will convert the integer value into dd/MM/yyyy format by extracting dd, MM, and yyyy parts separately using arithmetic operation and add / between MM and yyyy parts. It is then converted into VARCHAR datatype. CONVERT function with style 103 is used to convert the formatted string into a proper date value.


2 Answers

In order to be independent of the language and locale settings, you should use the ISO 8601 YYYYMMDD format - this will work on any SQL Server system with any language and regional setting in effect:

SELECT    CAST(       CAST(year AS VARCHAR(4)) +       RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +       RIGHT('0' + CAST(day AS VARCHAR(2)), 2)     AS DATETIME) 
like image 183
marc_s Avatar answered Sep 22 '22 13:09

marc_s


Pure datetime solution, does not depend on language or DATEFORMAT, no strings

SELECT     DATEADD(year, [year]-1900, DATEADD(month, [month]-1, DATEADD(day, [day]-1, 0))) FROM     dbo.Table 
like image 36
gbn Avatar answered Sep 25 '22 13:09

gbn