Skip to content

Instantly share code, notes, and snippets.

@szul
Last active September 17, 2015 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szul/64d32d763b074ce6d994 to your computer and use it in GitHub Desktop.
Save szul/64d32d763b074ce6d994 to your computer and use it in GitHub Desktop.
Using a CTE for a recursive select
WITH CTE_ITEM_HIERARCHY AS
(
SELECT i.[ItemID]
,i.[Text]
,i.[ParentItemID]
FROM [dbo].[Item] AS i
WHERE i.[ParentItemID] = 0
UNION ALL
SELECT i2.[ItemID]
,i2.[Text]
,i2.[ParentItemID]
FROM CTE_ITEM_HIERARCHY AS cte
INNER JOIN [dbo].[Item] i2
ON i2.[ParentItemID] = cte.[ItemID]
)
SELECT * FROM CTE_ITEM_HIERARCHY
OPTION (MAXRECURSION 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment