Trying to get the number of incidents in my database, in the format:
date numberOfIncidents
date numberOfIncidents
date numberOfIncidents
date numberOfIncidents
I supply the start date / end date to my SQL stored procedure, but if there is no entry in the database for a particular date (because no incidents occured) then I wont get the full range back.
What I want is every single date to be returned between my start/end dates, with a value next to it.
Is this possible in SQL Server?
Yes - you can use a Numbers Table a bit like this (probably not overly efficient, and assumes incident dates have zero time parts (00:00:00) - if this is not true you'll need to make the time zero test the difference in dates):
Then use as..
It's a bit hard to tell without more information, but it sounds like what you need to do is create a temp table that has your complete date range in it, then use a left join to join it to your numberOfIncidents data. Then you'll get all the dates, even if there were no incidents.
EDIT: To create the temp table, you could just create a loop that goes from your startDate to your endDate, and insert those rows into the db.
Try this code:
You can use a recursive common table expression to produce the date range and then join it to your incidents.
By default, SQL Server limits the recursive definition to 100 rows. If you need more than 100 date rows, append
OPTION (MAXRECURSION n)
to the end of the query, changingn
to the required number of rows.How about something like this (admittedly this isn't a stored procedure, but it should be useful):