创建用于数字引用的 SQL 表



对不起,我对这一切还很陌生。我需要创建一个包含两列的 SQL 表:PrimaryNumber、ThousandRange

主数应用 1 - 20,000 之间的整数填充。 千范围应填充主数的相应范围。

例如:

PrimaryNumber       ThousandRange
1000                1000-1999
1001                1000-1999
1002                1000-1999
1003                1000-1999
...                 ...
2000                2000-2999
2001                2000-2999
2002                2000-2999
2003                2000-2999

等等。

一种方法case表达式相当复杂。 一个更有趣的方法是玩弦和算术:

select (floor(primarynumber / 1000)*1000 || '-' ||
(floor(primarynumber / 1000)*1000 + 999)
) as thousandrange

这使用 ANSI 标准语法。 这个或类似的东西应该在大多数数据库中工作。 例如,这里有一个SQL小提琴。

编辑:

您还想创建表。 SQL Server有点棘手。 这是一种方法:

with n as (
select 1000 as n union all
select n + 1
from n
where n < 20000
)
select n as primarynumber,
replace(replace('[1]-[2]', '[1]', floor(n / 1000)*1000), '[2]', floor(n / 1000)*1000 + 999) as thousandrange
from n
option (maxrecursion 0);

这是另一个演示。

试试这个...

DECLARE @startnum INT=1000 
DECLARE @endnum INT=20000 
;WITH cte (primarynumber, thousandrange) 
AS (SELECT @startnum, 
@startnum 
UNION ALL 
SELECT primarynumber + 1, 
( primarynumber + 1 ) - ( ( primarynumber + 1 ) % 1000 ) 
FROM   cte 
WHERE  primarynumber < @endnum) 

SELECT primarynumber, 
Cast(thousandrange AS NVARCHAR(max)) + '-' + Cast(thousandrange+999 AS NVARCHAR(max)) AS thousandrange 
FROM   cte 
OPTION (maxrecursion 20000) 

输出。。。

+---------------+---------------+
| primarynumber | thousandrange |
+---------------+---------------+
| 1000          | 1000-1999     |
| 1001          | 1000-1999     |
| 1002          | 1000-1999     |
| ---           |               |
| 2783          | 2000-2999     |
| 2784          | 2000-2999     |
| 2785          | 2000-2999     |
| ---           |               |
| 7259          | 7000-7999     |
| 7260          | 7000-7999     |
| 7261          | 7000-7999     |
| ---           |               |
| 13737         | 13000-13999   |
| 13738         | 13000-13999   |
| 13739         | 13000-13999   |
| ---           |               |
| 17762         | 17000-17999   |
| 17763         | 17000-17999   |
| 17764         | 17000-17999   |
| ---           |               |
| 19998         | 19000-19999   |
| 19999         | 19000-19999   |
| 20000         | 20000-20999   |
+---------------+---------------+

演示:http://www.sqlfiddle.com/#!18/9eecb/15728/0

你只做一次,所以它真的不需要是一个"基于集合"的查询。一个简单的循环将完美地工作。

create table N (PrimaryNumber int not null, ThousandRange varchar(12) not null);
declare @n int = 1;
while @n <= 20000
begin
insert into N (PrimaryNumber, ThousandRange) values
(@n, cast(@n / 1000 * 1000 as varchar(8)) + '-' +
cast(@n / 1000 * 1000 + 999 as varchar(8));
set @n = @n + 1;
end
commit;

在 SQL Server 中,这使用标准的整数除法。

最新更新