Creating date in SQL Server 2008 Creating date in SQL Server 2008 sql sql

Creating date in SQL Server 2008


You could use something like this to make your own datetime:

DECLARE @year INT = 2012DECLARE @month INT = 12DECLARE @day INT = 25SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @month) + '-' + CONVERT(VARCHAR, @day) AS DATETIME)


Using the 3 from your example, you could do this:

dateadd(dd, 3 -1, dateadd(mm, datediff(mm,0, current_timestamp), 0))

It works by finding the number of months since the epoch date, adding those months back to the epoch date, and then adding the desired number of days to that prior result. It sounds complicated, but it's built on what was the canonical way to truncate dates prior to the Date (not DateTime) type added to Sql Server 2008.

You're probably going to see other answers here suggesting building date strings. I urge you to avoid suggestions to use strings. Using strings is likely to be much slower, and there are some potential pitfalls with alternative date collations/formats.


CREATE FUNCTION  DATEFROMPARTS(    @year int,    @month int,    @day int)RETURNS datetimeASBEGIN     declare @d datetime     select @d =    CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @month) + '-' + CONVERT(VARCHAR, @day) AS DATETIME)    RETURN  @d ENDGO