如何生成两个数字之间的数字范围?
我有两个数字作为用户输入,例如 1000
和 1050
.
I have two numbers as input from the user, like for example 1000
and 1050
.
如何使用 sql 查询在单独的行中生成这两个数字之间的数字?我想要这个:
How do I generate the numbers between these two numbers, using a sql query, in seperate rows? I want this:
1000
1001
1002
1003
.
.
1050
推荐答案
使用 VALUES
关键字选择非持久值.然后使用 JOIN
s 生成很多很多的组合(可以扩展为创建数十万行甚至更多行).
Select non-persisted values with the VALUES
keyword. Then use JOIN
s to generate lots and lots of combinations (can be extended to create hundreds of thousands of rows and beyond).
短而快的版本(不是那么容易阅读):
Short and fast version (not that easy to read):
WITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM x ones, x tens, x hundreds, x thousands
ORDER BY 1
演示
更详细的版本:
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
ORDER BY 1
演示
两个版本都可以使用 WHERE
子句轻松扩展,将数字的输出限制在用户指定的范围内.如果你想复用它,你可以为它定义一个表值函数.
Both versions can easily be extended with a WHERE
clause, limiting the output of numbers to a user-specified range. If you want to reuse it, you can define a table-valued function for it.
相关文章