A CTE allows you to define a temporary named result set that available temporarily in the execution scope of a statement such as SELECT
, INSERT
, UPDATE
, DELETE
, or MERGE
.select statement
That immediately follow the cte.
syntax of cte
with CTE(column_1,column_2,.....)
as
query
select/update/delete/insert
with cte as (
select * from employee where salary>45000
)
select * from cte
example 2:
with cte as (
select * from employee e join department d on e.dept=d.dept_name where salary>45000
)
select * from cte
If we update the CTE it will update the base table
as
select * from
update
*** if cte is based on multiple table and if the update statement affect
more than one table,then update is not allowed.
but if its affect one table then it will be success(but not always)
Using multiple SQL Server CTE in a single query example
Using multiple SQL Server CTE in a single query example
with emp as (
select * from employee where salary>45000
),
dept as (
select * from department
)
select * from emp join dept on emp.dept=dept.dept_name
Recursive CTE:
A recursive common table expression (CTE) is a CTE that references itself. By doing so, the CTE repeatedly executes, returns subsets of data, until it returns the complete result set.
In general, a recursive CTE has three parts:
- An initial query that returns the base result set of the CTE. The initial query is called an anchor member.
- A recursive query that references the common table expression, therefore, it is called the recursive member. The recursive member is union-ed with the anchor member using the
UNION ALL
operator. - A termination condition specified in the recursive member that terminates the execution of the recursive member.