Monday, 13 January 2014

CTE & RECURSIVE CTE(Common Table Expression)

Common Table Expression
Simple CTE
Print 1 to N numbers
;
WITH CTE AS
(
    SELECT NoM=1
    UNION ALL
    SELECT NoM+1 FROM CTE WHERE NOM+1<=10
) SELECT * FROM CTE

Ans:



Find the Employees under manager 

;WITH X AS
(
    SELECT * FROM EMP WHERE mgr=7788
    UNION ALL
    SELECT e.* FROM x  INNER JOIN emp e ON e.empno=x.mgr
)
SELECT * FROM X

Ans:

Find Cumulative Salary of employees 

select SAL,(select SUM(sal) from emp e where e.empno<=a.empno)as CUM_SAL from emp a

No comments:

Post a Comment

EMP, DEPT Sample script

/****** Object:  Table [dbo].[DEPT]    Script Date: 19-05-2016 06:58:37 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET A...