Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trunc(sysdate) in SQL Server

What is the equivalent of:

TRUNC(SYSDATE) 

...in SQL Server 2005?

like image 462
Domnic Avatar asked Nov 11 '09 05:11

Domnic


People also ask

What is TRUNC Sysdate in SQL?

TRUNC(SYSDATE) removes the time element from the date. Any date that has been fed through the TRUNC function has a date of midnight. Consequently, TRUNC(SYSDATE) is always earlier than SYSDATE (unless you execute it on the very moment of midnight).

Is there TRUNC function in SQL Server?

SQL Server SPID – What is it? » In Oracle there is a function (trunc) used to remove the time portion of a date. In order to do this with SQL Server, you need to use the convert function. Convert takes 3 parameters, the datatype to convert to, the value to convert, and an optional parameter for the formatting style.

How do I truncate a date in SQL Server?

DECLARE @d datetime = '2020-02-02 02:02:02.002'; SELECT 'Input', @d; SELECT 'Truncated', DATETRUNC(millisecond, @d); Here's the result set, which illustrates that the truncated date is the same as the stored date.


2 Answers

Recommended:

DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

This is another alternative, but it's risky because of casting to a FLOAT. It's also been demonstrated to not scale performance as well as the DATEADD/DATEDIFF approach.

CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
like image 172
OMG Ponies Avatar answered Oct 04 '22 13:10

OMG Ponies


Another option is to use CONVERT (MSSQL 2008 and later) and either use an appropriate style or use a style that you can then SUBSTRING. I have no idea about the performance compared to the dateadd/datediff solution though.

e.g.

SELECT SUBSTRING(CONVERT(nvarchar(30), GETDATE(), 120), 1, 16)

Returns:

2012-01-03 15:30

Example using group that lists rows created per minute (presupposes a 'created' datetime column):

SELECT SUBSTRING(CONVERT(nvarchar(30), created, 120), 1, 16) as [minute]
, COUNT(1) as [per min]
FROM foo
GROUP BY SUBSTRING(CONVERT(nvarchar(30), created, 120), 1, 16)
like image 37
stoft Avatar answered Oct 04 '22 13:10

stoft