Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all dates between two dates [duplicate]

Tags:

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,

like image 446
Dnakk Jam Avatar asked Jul 08 '13 14:07

Dnakk Jam


People also ask

How can I get a list of dates between two dates?

We can get the dates between two dates with single method call using the dedicated datesUntil method of a LocalDate class. The datesUntill returns the sequentially ordered Stream of dates starting from the date object whose method is called to the date given as method argument.

How do I get all dates between two dates in SQL?

DECLARE @MinDate DATE = '20140101', @MaxDate DATE = '20140106'; SELECT TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1) Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a. object_id) - 1, @MinDate) FROM sys. all_objects a CROSS JOIN sys.

How do I create an array between two dates in Excel?

Since Excel dates are whole numbers, all you need to do is ask Sequence() to insert an array from a Start Date to an End Date. Sequence(1 + EndDate – StartDate, 1, StartDate) the formula will spill the dates into the cells below.


2 Answers

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 ║ ╚════════════╝ 
like image 178
Lamak Avatar answered Oct 04 '22 22:10

Lamak


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) 
like image 37
SAM Avatar answered Oct 04 '22 22:10

SAM