November 29, 2011 7 Comments
As part of my planning for the SQL Saturday Presentation in Vancouver I am creating an hour long presentation on Common Table Expressions.
The easiest way to do a recursive query in SQL server is to use a recursive CTE (Common Table Expression).
What is a Common Table Expression in SQL Server?
- Similar to the ease of a temporary table without the performance problems of a temp table.
- Temporary Named Result Set
- Acts like a temporary view
- Can be use to
- Create a recursive query
- Simplify a query by using a result set multiple times
- Self JOIN a subquery without running the subquery twice
Here is a transact SQL sample based on the AdventureWorksLt database demonstrating a CTE for a recursive query.
WITH CategoryCTE(CategoryId, Name, Level) AS (
SELECT ProductCategoryId AS CatId,
Name, 0 as Level
WHERE ParentProductCategoryId is NULL
UNION ALL -- and now for the recursive part
SELECT c.ProductCategoryId AS CatId,
c.Name, ccte.CategoryId + 1 as Level
FROM saleslt.ProductCategory c
INNER JOIN CategoryCTE as ccte
ON ccte.CategoryId = c.ParentProductCategoryID
ORDER BY Level, Name;
CTE’s and Recursive CTE’s were first introduced in SQL Server 2005, and are available in 2008 and 2008R2 with the same syntax.
For another example of CTE’s (non-recursive) take a look at the query behind the Backup Set SQL Server Health Report.