从表中获取子节点

时间:2012-12-08 04:38:40

标签: sql sql-server-2008

有一个SQL表,如:

id, parentid, name 
1     0        Root
2     1        label 1
3     2        label 1.1
4     3        label 1.1.1
5     1        label 2
6     5        label 2.1
7     6        label 2.1.1

现在我想通过id 2/3/5等找到所有孩子。我该怎么做?

1 个答案:

答案 0 :(得分:1)

假设table1是您的表名,@input包含输入值

DECLARE @input INT = 2;
DECLARE @parent INT = 0;
DECLARE @name NVARCHAR(200); --same type with name column
SELECT @parent = parentid, @name = name FROM table1 WHERE id = @input;
IF @parent = 0
   SELECT * FROM table1 WHERE id <> @input
ELSE
   SELECT * FROM table1 WHERE name LIKE (@name + '%')

如果名称字段的格式与示例中的格式相同,则可以执行此操作。

对于递归SQL,请参考以下方式:

WITH temptable (id, parentid, name) AS
(
  SELECT id, parentid, name
  FROM table1 t1
  WHERE t1.id = 1
  UNION ALL
  SELECT t2.id, t2.parentid, t2.name
  FROM table1 t2, temptable t3
  WHERE t2.parentid = t3.id
)
SELECT id, parentid, name 
FROM temptable
WHERE parentid <> 0