欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SQL中的循环获取根节点

程序员文章站 2022-05-24 18:18:14
...

方法一:

DECLARE @employeeid INT;
set @employeeid = 8115;

DECLARE @id INT;
DECLARE @pid int;
DECLARE @level int;
SET @id=-1
--获取父节点id
SELECT @id = RecID, @pid = PID, @level = [Level]
FROM Organization.dbo.OfficePlace
WHERE recid= (SELECT TOP 1 OfficePlaceID FROM Organization.dbo.Employees WHERE [email protected])

WHILE (@pid!=-1)
BEGIN
  SELECT @id = RecID,@pid = PID,@level = [Level] 
  FROM Organization.dbo.OfficePlace
  where status=0 AND [email protected]
END
PRINT @id

方法二: DECLARE @officePlaceId INT;

DECLARE @officePlaceId INT;
 set @officePlaceId=117;

 DECLARE @id INT;
        SELECT  @id = ISNULL(( SELECT TOP 1
                                        pid
                               FROM     Organization.dbo.OfficePlace
                               WHERE    RecID = @officePlaceId
                                        AND pid <> -1
                                        AND pid IS NOT NULL
                             ), -1) 
        WHILE @@ROWCOUNT > 0
            AND @id > 0
            BEGIN
                SELECT  @id = pid
                FROM    Organization.dbo.OfficePlace
                WHERE   RecID = @id
                        AND pid <> -1
                        AND pid IS NOT NULL
            END
        print @id 

  

你觉得那种好呢?