I want to get all dates between startend
and Enddate
.I used between to get the desired result. But the between function skipping the current date.
Declare @StartDate Datetime ='2014-04-01 11:13:37'
,@EndDate datetime ='2014-04-04 11:13:37'
Query:-
Select * from table where date between @Startdate and @EndDate
Current Result:-
2014-04-02 11:13:37
2014-04-03 11:13:37
2014-04-04 11:13:37
Expected result:-
2014-04-01 11:13:37
2014-04-02 11:13:37
2014-04-03 11:13:37
2014-04-04 11:13:37
You could create a procedure like this:
CREATE PROCEDURE getAllDaysBetweenTwoDate
(
@StartDate DATETIME,
@EndDate DATETIME
)
AS
BEGIN
DECLARE @TOTALCount INT
SET @StartDate = DATEADD(DAY,-1,@StartDate)
Select @TOTALCount= DATEDIFF(DD,@StartDate,@EndDate);
WITH d AS
(
SELECT top (@TOTALCount) AllDays = DATEADD(DAY, ROW_NUMBER()
OVER (ORDER BY object_id), REPLACE(@StartDate,'-',''))
FROM sys.all_objects
)
SELECT AllDays From d
RETURN
END
GO
Courtesy: Find All the Days Between Two Dates
You Can Try this
Declare @StartDate Date ='2014-04-01'
,@EndDate date ='2014-04-04'
(OR)
Declare @StartDate Datetime ='2014-04-01 00:00:00'
,@EndDate datetime ='2014-04-04 12:59:59'
Query:-
Select * from table where date between @Startdate and @EndDate
Your query works for me perfectly.
DECLARE @StartDate DATETIME = '2014-04-01 11:13:37',
@EndDate DATETIME = '2014-04-04 11:13:37';
WITH cte_dates
AS
(
SELECT DATEADD(MONTH,-1,@startDate) dates --get dates from a month before start date
UNION ALL
SELECT DATEADD(DAY,1,dates)
FROM cte_dates
WHERE dates < DATEADD(MONTH,1,@EndDate) --up to a month after end date
)
SELECT dates
FROM cte_dates
WHERE dates BETWEEN @Startdate AND @EndDate
Results:
dates
-----------------------
2014-04-01 11:13:37.000
2014-04-02 11:13:37.000
2014-04-03 11:13:37.000
2014-04-04 11:13:37.000
This means that it's probably an issue with your data, specifically the time section. If you don't need to look at time and only need specific dates, try this instead:
DECLARE @StartDate DATE = '2014-04-01',
@EndDate DATE = '2014-04-04';
SELECT *
FROM yourTable
WHERE CAST([date] AS DATE) BETWEEN @startDate AND @EndDate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.