华赐软件 Bootstrap3

子节点深度级联获取所有父节点sql

子节点深度级联获取所有父节点:

View Code
USE [DBName]
GO
/****** Object:  StoredProcedure [dbo].[P_GetCategoryParentByCategoryID]   ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        xxx
-- Create date: xxx
-- Description:    子节点向上获取所有节点
-- =============================================
Create procedure [dbo].[P_GetCategoryParentByCategoryID]
(
    @CategoryID nvarchar(50)
)
AS
BEGIN
    DECLARE @tb table(CateID uniqueidentifier,CateName varchar(50),ParentID uniqueidentifier,Remark varchar(256),DisplayName varchar(50),[Level] int)
    DECLARE @tempTb table(CateID uniqueidentifier,CateName varchar(50),ParentID uniqueidentifier,Remark varchar(256),DisplayName varchar(50))
    DECLARE @cateID uniqueidentifier
    DECLARE @cursor cursor
    SET @cursor = cursor for select CateID from dbo.T_Sys_Category where CateID = @CategoryID
    OPEN @cursor 
    FETCH NEXT FROM @cursor INTO @cateID
    WHILE(@@fetch_status=0)
    BEGIN 
        INSERT INTO @tb SELECT * FROM dbo.Fn_GetCategoryParent(@cateID)
        FETCH NEXT FROM @cursor INTO @cateID
    END 
    CLOSE @cursor 
    DEALLOCATE @cursor
    INSERT INTO @tempTb SELECT DISTINCT CateID,CateName,ParentID,Remark,DisplayName from @tb
    SELECT * FROM @tempTb ORDER BY LEFT(CateID,18) DESC
END

 

View Code
USE [DBName]
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_GetCategoryParent]   ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create FUNCTION [dbo].[Fn_GetCategoryParent]
(
@Id UNIQUEIDENTIFIER
)
RETURNS @tb TABLE(CateID UNIQUEIDENTIFIER,CateName VARCHAR(50),ParentID UNIQUEIDENTIFIER,DisplayName VARCHAR(50),
    Remark VARCHAR(256), [Level] int)
AS
BEGIN
    DECLARE @i INT
    SET @i = 1
    INSERT INTO @tb SELECT CateID,CateName,ParentID,Remark,DisplayName,0 FROM dbo.T_Sys_Category WHERE CateID = @id
    INSERT INTO @tb SELECT CateID,CateName,ParentID,Remark,DisplayName,@i FROM dbo.T_Sys_Category 
    WHERE CateID = (SELECT ParentID FROM dbo.T_Sys_Category WHERE CateID = @Id)
    --如果没有新的值插入,循环结束
    WHILE @@rowcount<>0
    BEGIN
        SET @i = @i + 1;
        INSERT INTO @tb
            SELECT a.CateID,a.CateName,a.ParentID,a.Remark,a.DisplayName,@i
        FROM 
            dbo.T_Sys_Category a, @tb b
        WHERE
            a.CateID = b.ParentID and b.Level = @i - 1
    END
    RETURN    
END

 

posted @ 2012-12-25 10:44  OpenCsharp.Net  阅读(407)  评论(0编辑  收藏  举报
华赐软件 Bootstrap3
w.huacisoft.com">华赐软件 Bootstrap3