如何在sql server表中查找表列的所有子项?

时间:2012-09-27 16:17:53

标签: .net sql sql-server-2008

我有一个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,它应该返回其父级为Customers且其子级为子级的所有行等等。

2 个答案:

答案 0 :(得分: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);

here is a working sqlfiddle让你尝试。

答案 1 :(得分: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 = ''