csefaruk
csefaruk

Reputation: 191

Get child nodes from a table

In have an SQL table like:

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

Now I want to find all child by id 2/3/5 etc.. How do I do this?

Upvotes: 0

Views: 92

Answers (1)

Han
Han

Reputation: 3324

Suppose table1 is your table name and @input contains the input value

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 + '%')

This can be done if the name field has format like in your example.

For recursive SQL refer this way:

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

Upvotes: 2

Related Questions