记一次SqlServer骚操作——递归
最进需要用到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
兼容MSSQL2008以下的版本
正向查找
--首先我们将需要递归查到的元素写入#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
MSSQL2008以后的版本
正向查找
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