Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check date between two dates in T-SQL

I have a stored procedure where want check that a date is between a fixed date and the current date/time (with GETDATE()):

SELECT
    a, b
FROM myTbl
WHERE
    DATE BETWEEN 'Day start datetime' AND GETDATE()

...for example :

WHERE
    DATE BETWEEN '2013-09-10 00:00:00.00' AND 'GETDATE()'

How to do it?

like image 833
GeoVIP Avatar asked Sep 10 '13 07:09

GeoVIP


People also ask

How do you see if a date is between two dates in SQL?

SQL Server DATEDIFF() Function The DATEDIFF() function returns the difference between two dates.

How can I get date between two dates in SQL Server?

How do I count days between two dates in SQL Server? To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function.

How do I select data between two times in SQL?

The time is in a 24-hour format. Syntax: SELECT * FROM TABLE_NAME WHERE DATE_TIME_COLUMN BETWEEN 'STARTING_DATE_TIME' AND 'ENDING_DATE_TIME';

How do I select a specific date range in SQL?

SELECT * FROM YourTable. WHERE [dateColumn] >DATEADD(day,1,'4/25/2022') AND [dateColumn] <= DATEADD(day,1,'4/26/2022') AND DATEPART(hh,[dateColumn]) >= 7 AND DATEPART(hh,[dateColumn]) <= 19.


3 Answers

A pair of DATEADD/DATEDIFF calls will round a date down to the previous midnight:

SELECT a , b
FROM myTbl
WHERE DATE BETWEEN DATEADD(day,DATEDIFF(day,0,GETDATE()),0) and GETDATE()

Alternatively, if you're on SQL Server 2008 or later:

SELECT a , b
FROM myTbl
WHERE DATE BETWEEN CONVERT(date,GETDATE()) and GETDATE()
like image 133
Damien_The_Unbeliever Avatar answered Oct 24 '22 01:10

Damien_The_Unbeliever


'GETDATE()' is a string literal, GETDATE() is a T-SQL function.

Your query should look like:

SELECT a , b
FROM myTbl
WHERE DATE BETWEEN '2013-09-10 00:00:00.0' and GETDATE()
like image 30
Darren Avatar answered Oct 24 '22 03:10

Darren


I think WHERE DATE BETWEEN '2013-09-10 00:00:00.00' and GETDATE() (without the single quotes around the GETDATE() call) should work just fine.

like image 36
Onkel Toob Avatar answered Oct 24 '22 03:10

Onkel Toob