1

我有一个名为“Services”的表,其中包含一个 ServiceID、一个 ParentID 和一个 Description,其中 ParentID 是另一条记录的 ServiceID。数据以这样一种方式设置,即形成项目的多级层次结构,并且“根”项目的 ParentID 设置为零。如何使用一个新字段进行查询,该字段显示每个记录的所有父级到根父级的线程。当然,根项目会将此字段设置为空白。以汽车为例,我想在该字段中分别输入“X3”和“Punto”这样的文本:

汽车 > 德国 > 宝马 > 四轮驱动 > X3

汽车 > 意大利 > FIAT > 前轮驱动 > Punto

我怀疑我应该有一个函数来提供 ServiceID 并执行必要的递归以获取包含线程描述的字符串值。尝试谷歌搜索一元关系,但找不到我需要的函数的代码示例。

提前致谢!

更新:

这是我的桌子的样子:

CREATE TABLE [dbo].[Services](
[ServiceID] [int] IDENTITY(1,1) NOT NULL,
[ParentID] [int] NULL,
[ServiceDescription] [nvarchar](250) NULL)
4

2 回答 2

1

这是一个通用示例。您可以复制、粘贴和运行它,它会显示输出。如果这可行,您应该能够修改表和列值以使其适用于您的情况。

If      Object_ID('dbo.Services') Is Not Null Drop Table [dbo].[Services];
Create  Table [dbo].[Services] (ServiceID Int Identity(1,1) NOT NULL, ParenServiceID Int NULL, ServiceDescription Nvarchar(250) NULL);

Insert  [dbo].[Services]
Select  null, 'Automobiles'
Union   All
Select  1, 'Germany'
Union   All
Select  2, 'BMW'
Union   All
Select  3, '4 Wheel Drive'
Union   All
Select  1, 'Italy'
Union   All
Select  5, 'FIAT'
Union   All
Select  4, 'X3'
Union   All
Select  6, 'Front Wheel Drive'
Union   All
Select  8, 'Punto';

With    recurCTE As
(
        Select  h.ServiceID, h2.ParenServiceID As nextParent, Convert(Varchar(max),Isnull(h2.ServiceDescription + ' > ','') + h.ServiceDescription) As Hierarchy
        From    [dbo].[Services] h
        Left    Join [dbo].[Services] h2
                On  h.ParenServiceID = h2.ServiceID
        Union   All
        Select  rc.ServiceID, h.ParenServiceID As nextParent, Convert(Varchar(max),Isnull(h.ServiceDescription + ' > ','') + rc.Hierarchy) As Hierarchy
        From    recurCTE rc
        Join    [dbo].[Services] h
                On  rc.nextParent = h.ServiceID
),      orderedResults As
(
        Select  ServiceID, Hierarchy
        From   (Select  Row_Number() Over (Partition By ServiceID Order By Len(Hierarchy) Desc) As lenPriID,
                        ServiceID,
                        Hierarchy
                From    recurCTE) As n
        Where   lenPriID = 1
)
Select  h.*, o.Hierarchy
From    orderedResults o
Join    [dbo].[Services] h
        On  o.ServiceID = h.ServiceID
Where   ServiceDescription In ('X3','Punto');
于 2013-03-27T16:26:25.317 回答
0

我会使用左连接到一些合理的限制(比如 20),然后连接字符串:

 declare @services table (ServiceID int , ParentID int,[Description] varchar(20))

 insert @services
 select 1,null,'automobiles' union
 select 2,null,'hotels' union
 select 3,1,'Germany' union
 select 4,3,'BMW' union
 select 5,3,'Audi' union
 select 6,2,'Hawaii' union
 select 7,2,'Australia'

 select  

 s.Description+'>'+s2.Description+'>'+isnull(s3.Description,'')+'>'+isnull(s4.Description,'')
 from @services s
 left join @services s2 on (s2.ParentID=s.ServiceID)
 left join @services s3 on (s3.ParentID=s2.ServiceID)
 left join @services s4 on (s4.ParentID=s3.ServiceID)
 left join @services s5 on (s5.ParentID=s4.ServiceID)
于 2013-03-27T16:08:48.303 回答