T-SQL-接收2个数字之间的空格

时间:2019-10-01 15:07:56

标签: sql-server tsql

我正在使用SQL Server2012。

我收到一个“最大数目” f.e. 201900005这告诉我范围从201900000开始(给出)。现在我想接收该范围内缺少的数字。

我已经查看了有关此问题的几个问题,但是我似乎无法使其正常工作。使用游标之间或游标来对照表本身进行检查。

Max Number = 201900005, Min Number = 201900000
test_table
+----------------+
|   test_number  |
+----------------+
|   201900001    |
|   201900003    |
|   201900004    |
+----------------+
result
+----------------+
|    missing     |
+----------------+
|   201900000    |
|   201900002    |
|   201900005    |
+----------------+

当前过程与“帮助”表一起使用,该表主要包含201900000和201900005之间的所有数字(实际情况更多),并将其与test_table中的一次数字进行比较。

如果有任何建议,我将不胜感激。

2 个答案:

答案 0 :(得分:1)

个人而言,我将使用Tally创建所有可能数字的列表,然后LEFT JOIN将该列表添加到您的表中并返回不匹配的行:

CREATE TABLE dbo.Test_Table (Test_Number int);
INSERT INTO dbo.Test_Table (Test_Number)
VALUES(201900001),(201900003),(201900004);
GO

DECLARE @Start int = 201900000,
        @End int = 201900005;

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP (@End - @Start +1) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 + @Start AS I
    FROM N N1, N N2, N N3) --1000 rows, if you need more, just add more
SELECT T.I
FROM Tally T
     LEFT JOIN dbo.Test_Table TT ON T.I = TT.Test_Number
WHERE TT.Test_Number IS NULL;

GO

DROP TABLE dbo.Test_Table;

DB<>Fiddle

答案 1 :(得分:1)

另一种选择是使用临时提示表和Union ALL

示例

Declare @R1 int = 201900000
Declare @R2 int = 201900005

Select Missing = N
 From  (
        Select Top (@R2-@R1+1) N=@R1-1+Row_Number() Over (Order By (Select NULL)) From  master..spt_values n1, master..spt_values n2 
        Union All
        Select test_number from test_table Where test_number between @R1 and @R2
       ) A
 Group By N
 Having count(*)=1

返回

Missing
201900000
201900002
201900005