How to create an arbitrary list in SQL. Its a little easier said than done. Heres a code snippet which will do just that. The biggest power of this, is running queries to figure out what kind of ranges do not have any data. For example, consider a table of values between 1 and 10000. If someone were to ask which unique set of numbers existed in the table, that would be pretty easy. But if someone were to ask which set of number did not exist in the table, that query would be pretty tough. You have nothing to join against.
DECLARE @lowInclusive INT = 3 DECLARE @highInclusive INT = 55 -- Declare a common table expression ;WITH generator AS ( -- In the base case, just select our first number as a row SELECT number FROM (VALUES(@lowInclusive)) AS base(number) UNION ALL -- Now select recursively from the common table until we reach our high number SELECT number + 1 FROM generator WHERE number < @highInclusive ) SELECT * FROM generator
There you have it. A row list of numbers. You can expand this do work with things like dates as well.
DECLARE @lowInclusive Date = GETUTCDATE() DECLARE @highInclusive Date = DATEADD(DAY, 30, @lowInclusive) -- Declare a common table expression ;WITH generator AS ( -- In the base case, just select our first number as a row SELECT d FROM (VALUES(@lowInclusive)) AS base(d) UNION ALL -- Now select recursively from the common table until we reach our high number SELECT DATEADD(DAY, 1, d) FROM generator WHERE d < @highInclusive ) SELECT * FROM generator
There you have it. The result ends up looking like this
And now you can easily join to figure out which days of the month someone forgot to pay their bills, or whatever.