I would like list dates between two date in a SQL Server stored procedure.
For example:
Date1: 2015-05-28
Date2: 2015-05-31
Results :
2015-05-29
2015-05-30
How to calculate all dates between two given dates?
Regards,
I would like list dates between two date in a SQL Server stored procedure.
For example:
Date1: 2015-05-28
Date2: 2015-05-31
Results :
2015-05-29
2015-05-30
How to calculate all dates between two given dates?
Regards,
You can use a numbers table:
DECLARE @Date1 DATE, @Date2 DATE
SET @Date1 = '20150528'
SET @Date2 = '20150531'
SELECT DATEADD(DAY,number+1,@Date1) [Date]
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(DAY,number+1,@Date1) < @Date2
Results:
╔════════════╗
║ Date ║
╠════════════╣
║ 2015-05-29 ║
║ 2015-05-30 ║
╚════════════╝
Use this,
DECLARE @start_date DATETIME = '2015-02-12 00:00:00.000';
DECLARE @end_date DATETIME = '2015-02-13 00:00:00.000';
WITH AllDays
AS ( SELECT @start_date AS [Date], 1 AS [level]
UNION ALL
SELECT DATEADD(DAY, 1, [Date]), [level] + 1
FROM AllDays
WHERE [Date] < @end_date )
SELECT [Date], [level]
FROM AllDays OPTION (MAXRECURSION 0)
pass the @start_date and @end_date as SP parameters.
Result:
Date level
----------------------- -----------
2015-02-12 00:00:00.000 1
2015-02-13 00:00:00.000 2
(2 row(s) affected)
Create a stored procedure that does something like the following:
declare @startDate date;
declare @endDate date;
select @startDate = '20150528';
select @endDate = '20150531';
with dateRange as
(
select dt = dateadd(dd, 1, @startDate)
where dateadd(dd, 1, @startDate) < @endDate
union all
select dateadd(dd, 1, dt)
from dateRange
where dateadd(dd, 1, dt) < @endDate
)
select *
from dateRange
Or better still create a calendar table and just select from that.
I made a calendar using:
http://social.technet.microsoft.com/wiki/contents/articles/22776.t-sql-calendar-table.aspx
then a Store procedure passing two dates and thats all:
USE DB_NAME;
GO
CREATE PROCEDURE [dbo].[USP_LISTAR_RANGO_FECHAS]
@FEC_INICIO date,
@FEC_FIN date
AS
Select Date from CALENDARIO where Date BETWEEN @FEC_INICIO AND @FEC_FIN;
You can create a stored procedure passing 2 dates
CREATE PROCEDURE SELECTALLDATES
(
@StartDate as date,
@EndDate as date
)
AS
Declare @Current as date = DATEADD(DD, 1, @BeginDate);
Create table #tmpDates
(displayDate date)
WHILE @Current < @EndDate
BEGIN
insert into #tmpDates
VALUES(@Current);
set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day
END
Select *
from #tmpDates
drop table #tmpDates