标签:sql HERE 测试 目录 sqlserver 创建 while 递归 问题
目录
? 最进需要用到sql递归更新数据的问题,因为需要兼容Sql Server 2000的语法,所以在Sql Server2008前后有两种不同的写法,这里简单记录一下。
CREATE TABLE Test
(
Id INT,
PId int
)
INSERT INTO Test VALUES(1,null)
INSERT INTO Test VALUES(2,1)
INSERT INTO Test VALUES(3,2)
INSERT INTO Test VALUES(4,3)
-- 1<<2<<3<<4
--首先我们将需要递归查到的元素写入#temp临时表
SELECT Id INTO #temp FROM Test WHERE Id=1
WHILE @@ROWCOUNT > 0
BEGIN
--查找子后写入临时表,并排除已经在临时表中的Id
INSERT INTO #temp SELECT Id FROM Test WHERE PId IN (SELECT Id FROM #temp) AND Id NOT IN (SELECT Id FROM #temp)
END
SELECT * FROM #temp
SELECT Id,PId INTO #temp FROM Test WHERE Id=4
WHILE @@ROWCOUNT > 0
BEGIN
INSERT INTO #temp SELECT Id,PId FROM Test WHERE Id IN (SELECT PId FROM #temp) AND Id NOT IN (SELECT Id FROM #temp)
END
SELECT * FROM #temp
WITH #temp AS
(
--首先我们将需要递归查到的元素写入#temp临时表
SELECT Id FROM Test WHERE Id=1
UNION ALL
--查找子后写入临时表,并排除已经在临时表中的Id
SELECT a.Id FROM Test a
INNER JOIN #temp b ON a.PId= b.Id
)
SELECT * FROM #temp
WITH #temp AS
(
SELECT Id,PId FROM Test WHERE Id=4
UNION ALL
SELECT a.Id,a.Pid FROM Test a
INNER JOIN #temp b ON a.Id= b.PId
)
SELECT * FROM #temp
标签:sql HERE 测试 目录 sqlserver 创建 while 递归 问题
原文地址:https://www.cnblogs.com/guodf/p/9846030.html