1

我有一个 sql 数据库表

CREATE TABLE [dbo].[LedgerGroups](
    [GroupName] [varchar](50) NOT NULL primary key,
    [GroupParent] [varchar](50) NULL
)

表中的记录是

-----GroupName------ ---GroupParent---

Bangalore Customers    Karnataka Customers
Chennai Customers      Tamilnadu Customers
Customers              NULL
Ernakulam Customers    Kerala Customers
Hubli Customers        Karnataka Customers
Karnataka Customers    Customers
Kerala Customers       Customers
Kollam Customers       Kerala Customers
Nagercoil Customers    Tamilnadu Customers
Suppliers              NULL
Tamilnadu Customers    Customers
Tirunelveli Customers  Tamilnadu Customers

我如何查询表以便我可以获得特定值的所有子项。例如,如果我给Customers它应该返回其父级是客户及其子级的子级的所有行,依此类推..

4

2 回答 2

2

这应该这样做:

DECLARE @Group VARCHAR(50)
SET @Group = 'Karnataka Customers'

;WITH CTE AS
(
  SELECT *
  FROM [dbo].[LedgerGroups]
  WHERE GroupParent = @Group
  UNION ALL
  SELECT B.*
  FROM CTE A
  INNER JOIN [dbo].[LedgerGroups] B
  ON A.GroupName = B.GroupPArent
)
SELECT *
FROM CTE
OPTION(MAXRECURSION 0);

是一个工作的 sqlfiddle供您尝试。

于 2012-09-27T17:58:28.983 回答
0

您可以将表连接到自身。此查询将返回所有父母和他们可能关联到的任何孩子:

SELECT Parent.GroupName, Parent.GroupParent
,Children.GroupName, Children.GroupParent
from LedgerGroup as Parent
LEFT JOIN LedgerGroup as Children on Parent.GroupName = Children.GroupParent
--  WHERE Parent.GroupName = ''
于 2012-09-27T16:23:25.107 回答