在sql server中生成序列

发布于 2024-10-21 17:00:52 字数 167 浏览 1 评论 0原文

我正在开发一个函数,该函数将采用一个小数和一个大数作为参数,并返回一个包含其间(包括在内)所有内容的表。

我知道我可以使用游标并增加一个变量,每次迭代将其添加到基于范围的表中,但如果可能的话,我宁愿避免使用游标。还有其他人有关于执行此操作的方法的建议吗? (当我打字时,我想可能是 CTE,我会去调查)。

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝情姑娘 2024-10-28 17:00:52

是的,您可以使用递归 CTE 来执行此操作。例如,要生成 10 到 20 之间的数字(含 10 和 20):

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

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
瞄了个咪的 2024-10-28 17:00:52

只需创建一个带索引的永久辅助数字表即可完成。这将优于任何其他方法。

请参阅 Jeff Moden 的回答以了解更多详细信息以及用于填充此类的脚本一张桌子。如果由于某种原因这不是一个选项,根据链接答案中的性能测试,这应该会击败递归 CTE。

   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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文