Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a table of dates between x and y in sql server 2005

I just want a quick way (and preferably not using a while loop)of createing a table of every date between date @x and date @y so I can left outer join to some stats tables, some of which will have no records for certain days in between, allowing me to mark missing days with a 0

like image 663
digiguru Avatar asked Sep 18 '08 18:09

digiguru


People also ask

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

SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2001-02-01 10:00:00' AND '2007-03-01 22:00:00';

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.

How do I generate days between two dates in SQL?

Use the DATEDIFF() function to retrieve the number of days between two dates in a MySQL database. This function takes two arguments: The end date. (In our example, it's the expiration_date column.)

Can you use between with dates SQL?

The SQL BETWEEN OperatorThe values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.


2 Answers

Strictly speaking this doesn't exactly answer your question, but its pretty neat.

Assuming you can live with specifying the number of days after the start date, then using a Common Table Expression gives you:

WITH numbers ( n ) AS (
        SELECT 1 UNION ALL
        SELECT 1 + n FROM numbers WHERE n < 500 )
    SELECT DATEADD(day,n-1,'2008/11/01') FROM numbers
    OPTION ( MAXRECURSION 500 )
like image 53
BigJump Avatar answered Nov 15 '22 18:11

BigJump


I would create a Calendar table that just contained every date from a suitable start date until a suitable end date. This wouldn't take up much space in your database and would make these types of query child's play.

select  ...
from    Calendar
        left outer join
        ...
where   Calendar.Date >= @x
and     Calendar.Date <= @y
like image 34
Garry Shutler Avatar answered Nov 15 '22 17:11

Garry Shutler