您的位置:首页 > 其它

CTE(common table expression)

2010-04-13 11:27 295 查看
CTE的生命周期在于一次select、update、delete的执行

CTE最大的特点是可以自引用

下面是一个例子:

表中的数据

parent child id

kk yu 2

g m 3

yu m 4

m ml 5

递归找出所有"kk"的孩子集合(包括kk)

;with demo(parent,child,updatedate,id)

as

(

select parent,child,updatedate,id from table_1 where parent = 'kk'

union all

select t1.parent,t1.child,t1.updatedate,t1.id from demo

join table_1 t1 on demo.child = t1.parent

)

select * from demo

CTE Recursive Semantics

WITH cte_name ( column_name [,...n] )

AS

(

CTE_query_definition –- Anchor member is defined.

UNION ALL

CTE_query_definition –- Recursive member is defined referencing cte_name.

)

-- Statement using the CTE

SELECT *

FROM cte_name

The semantics of the recursive execution is as follows:

Split the CTE expression into anchor and recursive members.

Run the anchor member(s) creating the first invocation or base result set (T0
).

Run the recursive member(s) with Ti
as an input and Ti+1
as an output.

Repeat step 3 until an empty set is returned.

Return the result set. This is a UNION ALL of T0
to Tn
.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: