Sql在while循环中获取名称和父级

时间:2012-11-03 12:01:39

标签: sql sql-server

我有一个名为tblmodules的表,它有3列:moduleid,name,parent_id。列parent_id获取其他模块的值。例如:

Moduleid      Name       Parentid
--------     -----       --------
1           grandparent    Null
2            parent         1
3           child           2

我想要一个存储过程,它接受父级的Id和孩子的名字给出一个级别。所以我开发了以下内容。

        @moduleid bigint,
    @level int

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    declare @parentid bigint
    declare @name nvarchar(100)
    set @parentid = (select parentid from tblModules where ModuleId = @moduleid)


    declare @counter int
    set @counter = 1

    while @counter < @level
    begin

        set @parentid = (select parentid from tblModules where ModuleId = @parentid)
        set @name = (select Name from tblModules where ModuleId = @parentid)

        set @counter = @counter + 1
    end

    select @parentid AS ID
    select @name as Name

end

该过程正常工作并获取父级的正确ID,但名称与子级名称保持一致。对于ex,我正在执行它,给出值@moduleid:3和@level:2。 我得到结果ID:1这是正确的但名称:孩子而不是祖父母。有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

在我的脚本中,我使用CTE进行级别查找将与其ParentLevel(@level)连接的模块

CREATE PROCEDURE dbo.ParentLevelName
 (
  @moduleid bigint,
  @level int
  )
AS
BEGIN
  SET NOCOUNT ON;

  ;WITH ParentTree(Parentid, Moduleid, Name, ParentLevel)
  AS
   (
    SELECT Parentid, Moduleid, Name, 0 AS ParentLevel
    FROM tblmodules
    WHERE Parentid IS NULL
    UNION ALL
    SELECT t.Parentid, t.Moduleid, t.Name, p.ParentLevel + 1
    FROM tblmodules t JOIN ParentTree p ON t.Parentid = p.Moduleid 
    )
  SELECT p.Parentid, p.Moduleid, p.Name, p2.Name PerantLevelName
  FROM ParentTree p LEFT JOIN ParentTree p2 ON p.ParentLevel - @level = p2.ParentLevel
  WHERE p.Moduleid = @moduleid
END

SQL Fiddle上的演示