Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a recursive query in MSSQL 2005?

Tags:

Let's say I have the following table:

CustomerID ParentID Name ========== ======== ==== 1          null     John 2          1        James 3          2        Jenna 4          3        Jennifer 5          3        Peter 6          5        Alice 7          5        Steve 8          1        Larry  

I want to retrieve in one query all the descendants of James (Jenna,Jennifer,Peter, Alice, Steve). Thanks, Pablo.

like image 610
Pablo Retyk Avatar asked Oct 27 '08 07:10

Pablo Retyk


People also ask

How do you write a recursive query in SQL?

Recursion is achieved by WITH statement, in SQL jargon called Common Table Expression (CTE). It allows to name the result and reference it within other queries sometime later. Here is a sample. Query (SELECT 1 AS n) now have a name — R .

How do you create a recursive query?

First, specify the name of the view that you want to create in the CREATE RECURSIVE VIEW clause. You can add an optional schema-qualified to the name of the view. Second, add the SELECT statement to query data from base tables. The SELECT statement references the view_name to make the view recursive.

How recursive query works in SQL Server?

Recursion occurs because of the query referencing the CTE itself based on the Employee in the Managers CTE as input. The join then returns the employees who have their managers as the previous record returned by the recursive query. The recursive query is repeated until it returns an empty result set.

What is a recursive query explain with example?

A recursive query is one that is defined by a Union All with an initialization fullselect that seeds the recursion. The iterative fullselect contains a direct reference to itself in the FROM clause.


1 Answers

On SQL Server 2005 you can use CTEs (Common Table Expressions) :

with Hierachy(CustomerID, ParentID, Name, Level) as ( select CustomerID, ParentID, Name, 0 as Level     from Customers c     where c.CustomerID = 2 -- insert parameter here     union all     select c.CustomerID, c.ParentID, c.Name, ch.Level + 1     from Customers c     inner join Hierachy ch     on c.ParentId = ch.CustomerID ) select CustomerID, ParentID, Name from Hierachy where Level > 0 
like image 96
mathieu Avatar answered Sep 29 '22 19:09

mathieu