Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date serial in SQL?

How can I convert a day [1-31] and a month [1-12] and a year (all int), to a date serial IN SQL (without converting to varchar)?

like image 824
Stefan Steiger Avatar asked Jul 28 '10 16:07

Stefan Steiger


People also ask

What does Datefromparts do in SQL?

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

What is the format for date in SQL?

SQL Server comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS.

How do I declare a date in SQL?

To declare a date variable, use the DECLARE keyword, then type the @variable_name and variable type: date, datetime, datetime2, time, smalldatetime, datetimeoffset. In the declarative part, you can set a default value for a variable. The most commonly used default value for a date variable is the function Getdate().


2 Answers

Zero is 01 jan 1900 in SQL, so you can use this:

DATEADD(day, @dayval-1,
     DATEADD(month, @monthval-1,
         DATEADD(year, @yearval-1900, 0)
     )
)

Edit, Feb 2018

As the other answer says, since SQL Server 2012 (released after the original answer) we can use DATEFROMPARTS

 SELECT DATEFROMPARTS (@yearval, @monthval, @dayval)
like image 120
gbn Avatar answered Oct 04 '22 14:10

gbn


A few functions have been added in SQL Server 2012 which will allow you to do this with DATEFROMPARTS, DATETIMEFROMPARTS and TIMEFROMPARTS amongst others.

Example:

SELECT DATEFROMPARTS(2018,2,1) -- returns 2018-02-01
like image 38
jakdep Avatar answered Oct 04 '22 15:10

jakdep