另一个表中不存在的数字临时表

时间:2014-12-16 10:03:15

标签: sql sql-server sql-server-2008

我有一张名为 UsedNumbers

的表格

UsedNumbers 包含 1 AND 9999 范围内的数字。 数字可以在此范围内的任何位置。

我想创建临时表 #UnUsedNumbers

到目前为止,我发现代码会创建一个从1到9999的数字范围。但我不完全确定如何 INSERT 将其转换为临时表,然后仅提取执行的数字 UsedNumbers 中不存在。

;WITH x AS
(
    SELECT TOP (224) [OBJECT_ID] FROM sys.all_objects
)
SELECT TOP (9999) n = ROW_NUMBER() OVER (ORDER BY x.[object_id])
FROM x CROSS JOIN x AS y
ORDER BY n;

如果有人可以提供帮助,我想更多地了解这一点。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方式:

;WITH x AS
(
    SELECT TOP (224) [OBJECT_ID] FROM sys.all_objects
)
SELECT TOP (9999) n = ROW_NUMBER() OVER (ORDER BY x.[object_id])
FROM x CROSS JOIN x AS y
EXCEPT 
SELECT num
FROM UsedNumbers
ORDER BY n

答案 1 :(得分:0)

试试这段代码

;WITH NumberCTE AS
(
    SELECT TOP (224) [OBJECT_ID] FROM sys.all_objects
)
,
AllNumbersCTE AS
(
    SELECT TOP (9999)
        ROW_NUMBER() OVER(order by RS1.[OBJECT_ID]) AS ROWID
    FROM 
        NumberCTE AS RS1
    LEFT JOIN NumberCTE AS RS2 ON 1 = 1
)

SELECT ROWID FROM AllNumbersCTE WHERE ROWID NOT IN (SELECT Number FROM UsedNumbers)