views:

204

answers:

4

Possible Duplicate:
Create a date with T-SQL

Hi,

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?

Thanks,

b.

A: 
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
Agent_9191
that's a bad idea - this is dependent on the local settings for your date format.
marc_s
@marc_s understood, but depending on your deployment needs, it may be a mute point.
Agent_9191
+5  A: 

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)
marc_s
thanks, I did it that way too.
balint
+1  A: 

You could convert your values into a 'Decimal' datetime and convert it then to a real datetime column:

select cast(rtrim(year *10000+ month *100+ day) as datetime) as Date from DateTable

See here as well for more info.

Dominik Fretz
+1  A: 

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

SELECT
    DATEADD(year, [year], DATEADD(month, [month], DATEADD(day, [day], 0)))
FROM
    dbo.Table
gbn