日期:2014-05-17 浏览次数:20959 次
delete from table1 where id=(
select top 1 bid from
(
select count(*) count, a.id aid, b.id bid from table1 a join table1 b on a.id = b.pid and a.pid = b.id
)c
where count > 1);
/*id为部门 pid为上级部门*/
/*最好有个时间可以排序*/
DECLARE @t TABLE(dep VARCHAR(10),pardep VARCHAR(10));
INSERT INTO @t SELECT 'a','b'
UNION ALL SELECT 'b','c'
UNION ALL SELECT 'c','d'
UNION ALL SELECT 'b','a'
UNION ALL SELECT 'c','b'
UNION ALL SELECT 'd','c'
UNION ALL SELECT 'x','y'
;WITH c1 AS (
SELECT rn=ROW_NUMBER() OVER(ORDER BY GETDATE()),* FROM @T
)
SELECT * FROM (
SELECT a.*,b.rn AS rnx FROM c1 a JOIN c1 b ON a.dep=b.pardep AND a.pardep=b.dep
) x WHERE rn<rnx
/*
rn dep pardep rnx
-------------------- ---------- ---------- --------------------
1 a b 4
2 b c 5
3 c d 6
*/