Check whether specified Date is between two Dates in SQL Server

Last Reply 2 months ago By pandeyism

Posted 3 months ago

I have table which has date ranges stored

Sdate Edate
1-Jan-2019 10-Jan-2019
15-Mar-2019 20-Mar-2019
10-Apr-2019 25-Apr-2019
3-May-2019 2-Jun-2019

Now I want check whether 16-May-2019 falls any of these date ranges

According to me it falls last one (3-May-2019 to 2-June-2019)

So as it falls these range I Want return the result 'yes' if not then 'No'

 

Posted 2 months ago

Hi satabeach,

Refer below sample query.

SQL

DECLARE @TestDateRange AS TABLE(StarDate DATETIME,EndDate DATETIME)
INSERT INTO @TestDateRange VALUES('1-Jan-2019','10-Jan-2019')
INSERT INTO @TestDateRange VALUES('15-Mar-2019','20-Mar-2019')
INSERT INTO @TestDateRange VALUES('10-Apr-2019','25-Apr-2019')
INSERT INTO @TestDateRange VALUES('3-May-2019','2-Jun-2019')

DECLARE @Date DATETIME
SET @Date = '16-May-2019'
--SELECT * FROM @TestDateRange WHERE @Date BETWEEN StarDate AND EndDate
IF EXISTS(SELECT * FROM @TestDateRange WHERE @Date BETWEEN StarDate AND EndDate)
BEGIN
	SELECT 'YES'
END
ELSE
BEGIN
	SELECT 'NO'
END