如何在两个数字之间生成一系列数字? [英] How to generate a range of numbers between two numbers?

查看:34
本文介绍了如何在两个数字之间生成一系列数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数字作为用户输入,例如 10001050.

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 生成大量组合(可以扩展以创建数十万行甚至更多).

Select non-persisted values with the VALUES keyword. Then use JOINs 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.

这篇关于如何在两个数字之间生成一系列数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆