嘿我试图从我的表中获取缺失值,但我不知道如何在没有CTE和递归的情况下得到它。 下面是我目前的代码,但正如我之前所说,它适用于递归。
DROP TABLE #temp;
CREATE TABLE #temp (
val INT NULL
);
DECLARE @val AS INT = 1;
WHILE @val <= 10
BEGIN
INSERT #temp (val)
SELECT cast((RAND()*10) as int);
SET @val = @val + 1;
END
SELECT *
FROM #temp;
WITH CTE AS
(
SELECT nMin = MIN(t.val), MAX(t.val) as 'nMax'
FROM #temp t
UNION ALL
SELECT nMin + 1, nMax
FROM CTE
WHERE nMin < nMax
)
SELECT c.nMin
FROM CTE c
WHERE NOT EXISTS
(
SELECT val
FROM #temp
WHERE c.nMin = val
)
答案 0 :(得分:1)
您只需要一个没有缺失值的数字列表,这样您就可以进行反连接。
现在,您正尝试使用递归生成这些值。对系统表使用ROW_NUMBER更有效。您可以交叉连接系统表以获取任意数量的数字,并使用TOP子句限制结果。即使在没有用户表的数据库中,也会有系统定义的对象。
我留下了您的代码,以便您可以比较差异。 如果你经常使用它,那么在你的数据库中有一个数字表可能是值得的。也称为计数表。
CREATE TABLE #temp (
val INT NULL
);
DECLARE @val AS INT = 1;
WHILE @val <= 10
BEGIN
INSERT #temp (val)
SELECT cast((RAND()*10) as int);
SET @val = @val + 1;
END
SELECT *
FROM #temp ORDER BY val;
WITH CTE AS
(
SELECT nMin = MIN(t.val), MAX(t.val) as 'nMax'
FROM #temp t
UNION ALL
SELECT nMin + 1, nMax
FROM CTE
WHERE nMin < nMax
)
,CTE_NUMBERS AS
(
SELECT TOP(10)
ROW_NUMBER() OVER(ORDER BY (SELECT 1 as d)) as nMin
FROM sys.all_objects AS a
CROSS JOIN sys.all_objects AS b
)
SELECT c.nMin
FROM CTE_NUMBERS c
WHERE NOT EXISTS
(
SELECT val
FROM #temp
WHERE c.nMin = val
)
DROP TABLE #temp