2011-02-17 237 views
0

我需要一些幫助的是MS SQL Server查詢。我不是一個DBA。我有一個組織表的應用程序,它由父子關係:SQL Server樹查詢

CREATE TABLE [dbo].[Organizations](
    [OrgPK] [int] IDENTITY(1,1) NOT NULL, 
    [OrgParentFK] [int] NULL, 
    [OrgName] [varchar](200) NOT NULL, 
CONSTRAINT [PK__Organizations] PRIMARY KEY CLUSTERED 

的樣本數據是這樣的:

OrgPK, OrgParentFK, OrgName 
1, 0, Corporate 
2, 1, Department A 
3, 1, Department B 
4, 2, Division 1 
5, 2, Division 2 
6, 3, Division 1 
7, 6, Section 1 
8, 6, Section 2 

我試圖生成返回查詢org路徑基於給定的OrgPK。如果實施例給出OrgPK = 7的查詢將返回 '公司/部門B/1區/第1'

如果給OrgPk = 5返回字符串將是 '公司/部門A /司2'

謝謝你的幫助。

+0

你對`OrgParentFK`外鍵約束? – 2011-02-17 20:41:20

回答

1
WITH OrganizationsH (OrgParentFK, OrgPK, OrgName, level, Label) AS 
(
    SELECT OrgParentFK, OrgPK, OrgName, 0, CAST(OrgName AS VARCHAR(MAX)) As Label 
    FROM Organizations 
    WHERE OrgParentFK IS NULL 
    UNION ALL 
    SELECT o.OrgParentFK, o.OrgPK, o.OrgName, level + 1, CAST(h.Label + '/' + o.OrgName VARCHAR(MAX)) As Label 
    FROM Organizations o JOIN OrganizationsH h ON o.OrgParentFK = h.OrgPK 
) 

SELECT OrgParentFK, OrgPK, OrgName, level, Label 
FROM OrganizationsH 
WHERE OrgPK = 5 

H/T到marc_s

+1

您可能必須在您的「標籤」條目周圍放置`CAST(..... AS VARCHAR(MAX))`(否則您將得到:「Msg 240,Level 16,State 1,Line 11 - Types在遞歸查詢「OrganizationsH」的列「標籤」中的錨和遞歸部分之間不匹配。「 - 但除此之外:darn,打我吧!! :-) – 2011-02-17 21:15:33

0

它也可以通過創建一個標值函數求解:

-- SELECT [dbo].[ListTree](5) 
CREATE FUNCTION [dbo].[ListTree](@OrgPK int) 
RETURNS varchar(max) 
AS 
BEGIN 
    declare @Tree varchar(MAX) 
    set @Tree = '' 

    while(exists(select * from dbo.Organizations where [email protected])) 
    begin 
     select @Tree=OrgName+'/'[email protected], 
       @OrgPK=OrgParentFK 
     from dbo.Organizations 
     where [email protected] 

    end 
    return left(@Tree,len(@Tree)-1) 
END