For those who are not familiar with an auxiliary 'numbers' or 'tally' table in a database, it's essentially just a single-column table that stores a sequence integers - usually from 0 to whatever large-ish number is suitable (e.g a few hundred thousand to a couple million). For such a simple concept, these are surprisingly useful to have kicking around your database; generating a sequence of dates boils down to 3 LOC
select getdate() - n.Number
from dbo.Numbers n
where n < 180;
as opposed to the traditional eyesore
declare @Dates table ([Value] datetime);
declare @iter int = 0;
while @iter < 180
begin
insert into @Dates ([Value])
values (getdate() - @iter);
set @iter += 1;
end;
select [Value]
from @Dates;
Given some of the more sophisticated features available on the SEDE, such as execution plans, colored graphs, the ability to create stored procedures, etc..., I was a little surprised to find a numbers table missing from sys.tables
. To me, implementing this feature seems like a no-brainer:
- It should take like 45 seconds for someone to create; just dump some integers into a table and throw a couple of indexes on it
- Little-to-no maintenance; it's values don't need to be updated, deleted, etc... over time
- Requires a trivial amount of storage space
- Incredibly useful
How do we feel about this?
I ran a quick benchmark comparing a simple operation using a numbers table and a recursive CTE (YRMV). The former approach yielded a much simpler execution plan and required a radically lower number of logical reads. While these measurements are certainly not the be-all end-all justification for such a feature, I think the results are fairly compelling.
master.dbo.spt_values
wherename is null
. That contains 2048 sequential values. In my other environments, I have a CLR table-valuedGetRange()
function which creates an arbitrary range.master
database.