I need some help is MS SQL Server Query. I’m not much of a DBA. I have an application with an Organization Table which is made up of a parent-child relationship:
CREATE TABLE [dbo].[Organizations](
[OrgPK] [int] IDENTITY(1,1) NOT NUL开发者_高级运维L,
[OrgParentFK] [int] NULL,
[OrgName] [varchar](200) NOT NULL,
CONSTRAINT [PK__Organizations] PRIMARY KEY CLUSTERED
Sample data looks like this:
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
I'm trying to generate a query that returns an org path based on a given OrgPK. Example if given OrgPK = 7 the query would return 'Corporation/Department B/Division 1/Section 1'
If give OrgPk = 5 the return string would be 'Corporation/Department A/Division 2'
Thank you for your assistance.
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 to marc_s
It can also be solved by creating a scalar valued function:
-- 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 OrgPK=@OrgPK))
begin
select @Tree=OrgName+'/'+@Tree,
@OrgPK=OrgParentFK
from dbo.Organizations
where OrgPK=@OrgPK
end
return left(@Tree,len(@Tree)-1)
END
精彩评论