2

我有很多相似的結構表如下:如何讓所有從CTE分層數據在SQL Server 2005中的孩子和自己使用存儲過程

CREATE TABLE [dbo].[tbl_Hierarchy](
[ID] [int] NOT NULL, 
[ParentID] [int] NOT NULL, 
[Text] [nvarchar](100) NOT NULL, 
--other field irrelevant to my question 
) 

INSERT INTO dbo.tbl_Hierarchy VALUES(1,0,'parent1') 
INSERT INTO dbo.tbl_Hierarchy VALUES(2,0,'parent2') 
INSERT INTO tbl_Hierarchy VALUES(3,1,'child1') 
INSERT INTO tbl_Hierarchy VALUES(4,3,'grandchild1') 
INSERT INTO tbl_Hierarchy VALUES(5,2,'child2') 

你能幫我作爲一個存儲過程包括兩名寫出這樣帶表名和ID的參數?

例如,執行

EXEC usp_getChildbyID tbl_Hierarchy, 1 

當結果集應該是:

ID Text  Level 
1 parent1  1 
3 child1  2 
4 grandchild1 3 

非常感謝提前。

+0

@marc_s謝謝你編輯 –

回答

5

這個遞歸CTE應該做的伎倆。

WITH RecursiveCte AS 
(
    SELECT 1 as Level, H1.Id, H1.ParentId, H1.Text FROM tbl_Hierarchy H1 
    WHERE id = @Id 
    UNION ALL 
    SELECT RCTE.level + 1 as Level, H2.Id, H2.ParentId, H2.text FROM tbl_Hierarchy H2 
    INNER JOIN RecursiveCte RCTE ON H2.ParentId = RCTE.Id 
) 
SELECT Id, Text, Level FROM RecursiveCte 

如果你真的與過程的動態表,希望這會是一個解決辦法

CREATE PROCEDURE usp_getChildbyID 
    @TableName nvarchar(max), 
    @Id int 
AS 
BEGIN 

    DECLARE @SQL AS nvarchar(max) 
    SET @SQL = 
    'WITH RecursiveCte AS 
    (
     SELECT 1 as Level, H1.Id, H1.ParentId, H1.Text FROM ' + @TableName + ' H1 
     WHERE id = ' + CAST(@Id as Nvarchar(max)) + ' 
     UNION ALL 
     SELECT RCTE.level + 1 as Level, H2.Id, H2.ParentId, H2.text FROM ' + @TableName + ' H2 
     INNER JOIN RecursiveCte RCTE ON H2.ParentId = RCTE.Id 
    ) 
    select Id, Text, Level from RecursiveCte' 

    EXEC sp_executesql @SQL; 
END 

編輯:

的Sql小提琴例如:http://sqlfiddle.com/#!3/d498b/22

+0

可以這樣調用: EXEC usp_getChildbyID'tbl_Hierarchy',1 –

+1

一個'ORDER BY'子句需要最後的'SELECT'來確保結果以OP的請求順序返回。如果'@TableName'有點拗口,'QUOTENAME'可能會有所幫助。 – HABO

相關問題