SQL Select 'n' records without a Table

前端 未结 8 560
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 03:33

Is there a way of selecting a specific number of rows without creating a table. e.g. if i use the following:

SELECT 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
         


        
8条回答
  •  北海茫月
    2020-12-30 04:01

    Using spt_values table:

    SELECT TOP (1000) n = ROW_NUMBER() OVER (ORDER BY number) 
    FROM [master]..spt_values ORDER BY n;
    

    Or if the value needed is less than 1k:

    SELECT DISTINCT n = number FROM master..[spt_values] WHERE number BETWEEN 1 AND 1000;
    

    This is a table that is used by internal stored procedures for various purposes. Its use online seems to be quite prevalent, even though it is undocumented, unsupported, it may disappear one day, and because it only contains a finite, non-unique, and non-contiguous set of values. There are 2,164 unique and 2,508 total values in SQL Server 2008 R2; in 2012 there are 2,167 unique and 2,515 total. This includes duplicates, negative values, and even if using DISTINCT, plenty of gaps once you get beyond the number 2,048. So the workaround is to use ROW_NUMBER() to generate a contiguous sequence, starting at 1, based on the values in the table.

    In addition, to aid more values than 2k records, you could join the table with itself, but in common cases, that table itself is enough.

    Performance wise, it shouldn't be too bad (generating a million records, it took 10 seconds on my laptop), and the query is quite easy to read.

    Source: http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1

提交回复
热议问题