Generating a sequence in sql server

梦想与她 提交于 2019-12-01 05:31:18

问题


I am working on a function that will take a low number and a high number as paramaters and returns a table containing everything between (and including).

I know I could use a cursor and increment a variable adding it to a scope based table every iteration, but I would prefer to avoid a cursor if possible. Does anyone else have a suggestion for a way to do this? (As i'm typing this im thinking possibly a CTE, which I will go investigate).


回答1:


Just create an indexed permanent auxiliary numbers table and be done with it. This will out perform any other method.

See Jeff Moden's answer here for more details and a script to populate such a table. if for some reason that isn't an option this should beat the recursive CTE according to the performance tests in the linked answer.

   WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
        E02(N) AS (SELECT 1 FROM E00 a, E00 b),
        E04(N) AS (SELECT 1 FROM E02 a, E02 b),
        E08(N) AS (SELECT 1 FROM E04 a, E04 b),
        E16(N) AS (SELECT 1 FROM E08 a, E08 b),
        E32(N) AS (SELECT 1 FROM E16 a, E16 b),
   cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)
   SELECT N FROM cteTally
   WHERE N BETWEEN 10 AND 20



回答2:


Yes, you can use a recursive CTE to do this. For example to generate numbers between 10 and 20 inclusive:

WITH f AS
(
    SELECT 10 AS x
    UNION ALL
    SELECT x + 1 FROM f WHERE x < 20
)
SELECT * FROM f


来源:https://stackoverflow.com/questions/5279071/generating-a-sequence-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!