Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row where datetime column = today - SQL server noob

In sql 2005, instead of building a query from dateparts year, month and date,

is there an more succinct way of writing the where clause?

like image 644
Chin Avatar asked Apr 06 '10 07:04

Chin


People also ask

How do I query today's date in SQL?

To get the current date and time in SQL Server, use the GETDATE() function. This function returns a datetime data type; in other words, it contains both the date and the time, e.g. 2019-08-20 10:22:34 .

Is there a today function in SQL?

SQL Server provides several different functions that return the current date time including: GETDATE(), SYSDATETIME(), and CURRENT_TIMESTAMP.

How do I convert a datetime column to a date in SQL?

Since the date values are stored in SQL Server in YYYY-MM-DD format by default, extracting the date part from the DateTime data type returns the date in this format. As you can see from the script above, to convert the DateTime type column to Date, you can use the CAST function.


2 Answers

On SQL Server 2008, you would have a new DATE data type, which you could use to achieve this:

SELECT (list of fields) FROM dbo.YourTable WHERE dateValue BETWEEN     CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)) 

The CAST(GETDATE() AS DATE) casts the current date and time to a date-only value, e.g. return '2010-04-06' for April 6, 2010. Adding one day to that basically selects all datetime values of today.

In SQL Server 2005, there's no easy way to do this - the most elegant solution I found here is using numeric manipulation of the DATETIME to achieve the same result:

SELECT (list of fields) FROM dbo.YourTable WHERE dateValue BETWEEN     CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME) AND     DATEADD(DAY, 1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)) 
like image 152
marc_s Avatar answered Sep 21 '22 17:09

marc_s


In SQL 2000 and SQL 2005 you can use a nice select statement to remove the time component from a DateTime, ie

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

will return 6-Apr-2010 (well for today only).

So combined with marc_s's answer, you'd want

SELECT (list of fields) FROM dbo.YourTable WHERE dateValue BETWEEN DATEADD(dd, DATEDIFF(dd,0,'MY Date and Time, But I Only Want Date'), 0)  AND DATEADD(dd, DATEDIFF(dd,0,'MY Date and Time, But I Only Want Date'), 1) 

Edit: Changed to suit requirements, note the 1 in the second DateAdd (this adds the days it has been from the beginning to 1 (instead of 0), making it 7th Apr 2010 00:00:00) If you want 6th Apr 23:59:59 you take a second away from the second date

DATEADD(ss,-1,'My DateTime') 

Final Call would become

DATEADD(ss,-1,DATEADD(dd, DATEDIFF(dd,0,'MY Date and Time, But I Only Want Date'), 1)) 

Ok that's alot of info at once! Hope it all makes sense :)

like image 21
PostMan Avatar answered Sep 20 '22 17:09

PostMan