Last active
August 29, 2015 14:03
-
-
Save adrianvlupu/0574ebd1eaa60b51dc7c to your computer and use it in GitHub Desktop.
TSQL recursive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @id INT | |
SET @id = 7 | |
DECLARE @tmp TABLE (id INT , ParentId INT) | |
INSERT INTO @tmp VALUES(1,0) | |
INSERT INTO @tmp VALUES(2,0) | |
INSERT INTO @tmp VALUES(3,2); | |
INSERT INTO @tmp VALUES(4,3); | |
INSERT INTO @tmp VALUES(5,0); | |
INSERT INTO @tmp VALUES(6,0); | |
INSERT INTO @tmp VALUES(7,4); | |
INSERT INTO @tmp VALUES(8,5); | |
WITH parent AS | |
( | |
SELECT id, parentId from @tmp WHERE id = @id | |
UNION ALL | |
SELECT t.id, t.parentId FROM parent | |
INNER JOIN @tmp t ON t.id = parent.parentid | |
) | |
SELECT id FROM parent | |
WHERE id <> @id; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment