Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dates from date components in SQL (T-SQL)?

Tags:

sql

tsql

How can I construct native date data type values in SQL (T-SQL)?

I've added some examples, but please provide your own. My examples assume that the month and year are being stored (or are readily available) as integer values, but maybe your example will assume that the day and the month (or whatever) are stored as text. I can't see the future; surprise me.

like image 413
Kenny Evitt Avatar asked Apr 24 '11 19:04

Kenny Evitt


People also ask

What does date () do in SQL?

The DATE() function extracts the date part from a datetime expression.


2 Answers

SELECT DATEFROMPARTS(@Year, @Month, @Day)

(From SQL Server 2012)

like image 70
Martin Smith Avatar answered Oct 08 '22 01:10

Martin Smith


Why, with input data as strings one of the most obvious (and therefore hardly surprising, sorry) solutions would be:

SELECT
  mydate = CAST([year] + RIGHT('0' + [month], 2) + '01' AS datetime)
                                           /* or 'AS date' in SQL Server 2008+ */
FROM (
  SELECT [month] = '2',  [year] = '2011' UNION ALL
  SELECT [month] = '03', [year] = '2011' UNION ALL
  SELECT [month] = '5',  [year] = '2011' UNION ALL
  SELECT [month] = '12', [year] = '2011' UNION ALL
  SELECT [month] = '8',  [year] = '2084' UNION ALL
  SELECT [month] = '1',  [year] = '1940'
) x;
like image 34
Andriy M Avatar answered Oct 07 '22 23:10

Andriy M