CTE in SQL





USE demostart
GO

IF OBJECT_ID('Employees', 'U') IS NOT NULL
DROP TABLE dbo.Employees
GO
CREATE TABLE dbo.Employees
(
  EmployeeID int NOT NULL PRIMARY KEY,
  FirstName varchar(50) NOT NULL,
  LastName varchar(50) NOT NULL,
  ManagerID int NULL
)
GO
INSERT INTO Employees VALUES (101, 'Raj', 'Singh', NULL)
INSERT INTO Employees VALUES (102, 'Merry', 'Desouza', 101)
INSERT INTO Employees VALUES (103, 'Ajay', 'Sinha', 101)


---------------------------------------------------------------------------


WITH
  cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
  AS
  (
    SELECT EmployeeID, FirstName, LastName, ManagerID, 1
    FROM Employees
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
      r.EmpLevel + 1
    FROM Employees e
      INNER JOIN cteReports r
        ON e.ManagerID = r.EmpID
  )
SELECT
  FirstName + ' ' + LastName AS FullName,
  EmpLevel,
  (SELECT FirstName + ' ' + LastName FROM Employees
    WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID
CTE in SQL Reviewed by Rupesh on 04:20 Rating: 5

1 comment:

  1. Hi Rupesh,

    Please provide some explanation about the topic.

    ReplyDelete

All Rights Reserved by Technology from Developers Eye © 2014 - 2015
Powered By Blogger, Designed by Aadics
Disclaimers:: The information provided within this blogsite is for general informational purposes only. While we try to keep the information up-to-date and correct, there are no representations or warranties, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the information, products, services, or related graphics contained in this blogsite for any purpose.The author does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause.

Contact Form

Name

Email *

Message *

Powered by Blogger.