简体   繁体   中英

Temp table of numbers that do not exist in another table

I have a table called UsedNumbers

UsedNumbers contains number in the range of 1 AND 9999 . The numbers are can be anywhere in this range.

I want to create a temp table #UnUsedNumbers .

So far I found code create a range of numbers from 1 to 9999. But I'm not entirely sure how to INSERT this into a temp table and then extract only the numbers that do not exist in 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;

I would love to understand more about this if someone could help.

You could try something like:

;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

try this code

;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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM