CREATE PROCEDURE GetIDS
(
@PID int
)
AS
DECLARE
@higherID int,
@intCount int
set @higherID = @PID
declare @tb_Result TABLE(ID int)
declare @tb_Parent TABLE(ID int)
declare @tb_Child TABLE(ID int)
INSERT INTO @tb_Parent(ID) VALUES (@higherID)
SELECT @intCount = COUNT(*)
FROM [UserTable]
WHERE (PID = @higherID)
WHILE @intCount <> 0 -- 有下级
BEGIN
DELETE @tb_Child /* 清空子表 */
INSERT INTO @tb_Child(ID)
SELECT ID FROM [UserTable]
WHERE (PID in (SELECT ID FROM @tb_Parent))
SELECT @intCount = COUNT(*) FROM @tb_Child
INSERT INTO @tb_Result(ID) SELECT ID FROM @tb_Child
DELETE FROM @tb_Parent
INSERT INTO @tb_Parent(ID) SELECT ID FROM @tb_Child
END
insert into @tb_Result(ID) values (@higherID)