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?
SQL Server DATEFROMPARTS() Function The DATEFROMPARTS() function returns a date from the specified parts (year, month, and day values).
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With