43

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?

Community
  • 1
  • 1
balint
  • 3,391
  • 7
  • 41
  • 50
  • This has been asked a few times. See http://stackoverflow.com/questions/266924/create-a-date-with-t-sql – womp Dec 17 '09 at 19:11

4 Answers4

71

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
  • 732,580
  • 175
  • 1,330
  • 1,459
38

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
gbn
  • 422,506
  • 82
  • 585
  • 676
  • This does require SQL to be configured with 1900 as base date though – Adriaan Davel Dec 05 '17 at 10:27
  • @AdriaanDavel SQL Server (the question tags) is *always* base date 01 Jan 1900. https://learn.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql see "default value". – gbn Dec 05 '17 at 21:39
8

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,368
  • 9
  • 15
2
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
Agent_9191
  • 7,216
  • 5
  • 33
  • 57