Tuesday 21 May 2013

Recursive Queries using Common Table Expressions (CTE)

       Sometimes we have data in a Hierarchical format, and we are to perform some Insert/Update/Delete operation over there. In this situation if the DataBase Server is SQL Server 2000 or lower version, then the task becomes bit complex and need to apply the logic with the help of views, cursors, temp tables or any other object.

        But, if the Database Server is SQL Server 2005 or later version, then the task becomes easier and can implement the Common Table Expressions (CTE).

        Here is an example to elaborate the concept. Let's say we have table UserDetails as below :


UserIDCityNameParentID
U001MumbaiU001
U002BhopalU002
U003DelhiU003
U004BhopalU002
U005MumbaiU001
U006DelhiU003
U007MumbaiU001
U008DelhiU003
U009BhopalU002
U010MumbaiU001
U011DelhiU003
U012MumbaiU001


    Now from the above table we like to get all the users which come under the hierarchy of user having UserID as "U001".

  To get the above result, we will apply the CTE with below code :


;WITH CTE
AS
(
      SELECT * FROM UserDetails 
      WHERE UserID = 'U001'
      UNION ALL
       
      SELECT  MS.*
      FROM  UserDetails MS
              ON MP.UserID = MS.ParentID
              INNER JOIN CTE MP
)
SELECT * FROM CTE
ORDER BY UserID



 Executing the above code, we will get the below ouput :


UserIDCityNameParentID
U001MumbaiU001
U005MumbaiU001
U007MumbaiU005
U010MumbaiU007
U012MumbaiU005




 Reference: Govind Badkur(http://sqlserver20.blogspot.com)