Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating date in SQL Server 2008

Tags:

Is there something similar to DATEFROMPARTS(year, month, day) in SQL Server 2008? I want to create a date using the current year and month, but my own day of the month. This needs to be done in one line in order to be used in a computed column formula.

For Example (I'm not sure if it works because I do not have SQL Server 2012):

DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 3) 

Is there a way to do this in SQL Server 2008?

DATEFROMPARTS Seems only available in SQL Server 2012 (link)

like image 914
Jaiesh_bhai Avatar asked Oct 22 '13 16:10

Jaiesh_bhai


People also ask

How do I insert date in MS SQL?

Always use ANSI default string literal format for date i.e. YYYY-MM-DD like below. INSERT INTO EMPLOYEE (EMPID, FULLNAME, DESIGNATION, JOINING, SAL, DEPTNAME) VALUES(8976, 'JOHN', 'JOE', 'ANALYST', '1990-12-12', 30000, 'Analytics'); It will insert your data in RDBMS i.e. MySQL, PostgreSQL, SQL Server.

How can create date from month and year in SQL Server?

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


2 Answers

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.

like image 132
Joel Coehoorn Avatar answered Sep 20 '22 15:09

Joel Coehoorn


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

DECLARE @year INT = 2012 DECLARE @month INT = 12 DECLARE @day INT = 25  SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @month) + '-' + CONVERT(VARCHAR, @day)  AS DATETIME) 
like image 31
Ken Richards Avatar answered Sep 19 '22 15:09

Ken Richards