您的位置:首页 > 数据库

T-SQL with as 的用法(转) SQL 下的递归查询 SQL2005(CTE) ,SQL2000(Function 递归)

2014-07-05 22:38 507 查看
摘自: http://blog.csdn.net/bluefoxev/article/details/6779794
------- SQL2005 方法

一.WITH AS的含义
WITH AS短语,也叫做子查询部分(subquery factoring),可以让你做很多事情,定义一个SQL片断,该SQL片断会被整个SQL语句所用到。有的时候,是为了让SQL语句的可读性更高些,也有可能是在UNION ALL的不同部分,作为提供数据的部分。
特别对于UNION ALL比较有用。因为UNION ALL的每个部分可能相同,但是如果每个部分都去执行一遍的话,则成本太高,所以可以使用WITH AS短语,则只要执行一遍即可。如果WITH AS短语所定义的表名被调用两次以上,则优化器会自动将WITH AS短语所获取的数据放入一个TEMP表里,如果只是被调用一次,则不会。而提示materialize则是强制将WITH AS短语里的数据放入一个全局临时表里。很多查询通过这种方法都可以提高速度。
二.使用方法
先看下面一个嵌套的查询语句:

select * from person.StateProvince where CountryRegionCode in
(select CountryRegionCode from person.CountryRegion where Name like 'C%')

上面的查询语句使用了一个子查询。虽然这条SQL语句并不复杂,但如果嵌套的层次过多,会使SQL语句非常难以阅读和维护。因此,也可以使用表变量的方式来解决这个问题,SQL语句如下:

declare @t table(CountryRegionCode nvarchar(3))
insert into @t(CountryRegionCode) (select CountryRegionCode from person.CountryRegion where Name like 'C%')

select * from person.StateProvince where CountryRegionCode
in (select * from @t)

虽然上面的SQL语句要比第一种方式更复杂,但却将子查询放在了表变量@t中,这样做将使SQL语句更容易维护,但又会带来另一个问题,就是性能的损失。由于表变量实际上使用了临时表,从而增加了额外的I/O开销,因此,表变量的方式并不太适合数据量大且频繁查询的情况。为此,在SQL Server 2005中提供了另外一种解决方案,这就是公用表表达式(CTE),使用CTE,可以使SQL语句的可维护性,同时,CTE要比表变量的效率高得多。

下面是CTE的语法:

[ WITH <common_table_expression> [ ,n ] ]
<common_table_expression>::=
expression_name [ ( column_name [ ,n ] ) ]
AS
( CTE_query_definition )

现在使用CTE来解决上面的问题,SQL语句如下:

with
cr as
(
select CountryRegionCode from person.CountryRegion where Name like 'C%'
)

select * from person.StateProvince where CountryRegionCode in (select * from cr)

其中cr是一个公用表表达式,该表达式在使用上与表变量类似,只是SQL Server 2005在处理公用表表达式的方式上有所不同。

在使用CTE时应注意如下几点:
1. CTE后面必须直接跟使用CTE的SQL语句(如select、insert、update等),否则,CTE将失效。如下面的SQL语句将无法正常使用CTE:

with
cr as
(
select CountryRegionCode from person.CountryRegion where Name like 'C%'
)
select * from person.CountryRegion -- 应将这条SQL语句去掉
-- 使用CTE的SQL语句应紧跟在相关的CTE后面 --
select * from person.StateProvince where CountryRegionCode in (select * from cr)

2. CTE后面也可以跟其他的CTE,但只能使用一个with,多个CTE中间用逗号(,)分隔,如下面的SQL语句所示:

with
cte1 as
(
select * from table1 where name like 'abc%'
),
cte2 as
(
select * from table2 where id > 20
),
cte3 as
(
select * from table3 where price < 100
)
select a.* from cte1 a, cte2 b, cte3 c where a.id = b.id and a.id = c.id

3. 如果CTE的表达式名称与某个数据表或视图重名,则紧跟在该CTE后面的SQL语句使用的仍然是CTE,当然,后面的SQL语句使用的就是数据表或视图了,如下面的SQL语句所示:

-- table1是一个实际存在的表

with
table1 as
(
select * from persons where age < 30
)
select * from table1 -- 使用了名为table1的公共表表达式
select * from table1 -- 使用了名为table1的数据表

4. CTE 可以引用自身,也可以引用在同一 WITH 子句中预先定义的 CTE。不允许前向引用。

5. 不能在 CTE_query_definition 中使用以下子句:

(1)COMPUTE 或 COMPUTE BY

(2)ORDER BY(除非指定了 TOP 子句)

(3)INTO

(4)带有查询提示的 OPTION 子句

(5)FOR XML

(6)FOR BROWSE

6. 如果将 CTE 用在属于批处理的一部分的语句中,那么在它之前的语句必须以分号结尾,如下面的SQL所示:

declare @s nvarchar(3)
set @s = 'C%'
; -- 必须加分号
with
t_tree as
(
select CountryRegionCode from person.CountryRegion where Name like @s
)
select * from person.StateProvince where CountryRegionCode in (select * from t_tree)

CTE除了可以简化嵌套SQL语句外,还可以进行递归调用,关于这一部分的内容将在下一篇文章中介绍。

------- SQL2000 方法

摘自: http://bbs.csdn.net/topics/360215000
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([modeid] int,modename varchar(20),parentid int)
insert [tb]
select 100 ,'商品管理', 0 union all
select 101 ,'定单管理', 0 union all
select 102 ,'用户管理', 0 union all
select 104 ,'学院广告', 0 union all
select 105 ,'系统设置', 0 union all
select 106 ,'附件管理', 0 union all
select 107 ,'商品管理', 100 union all
select 108 ,'明细管理', 100 union all
select 109 ,'物流管理', 100 union all
select 110 ,'商品信息管理', 107 union all
select 111 ,'商品分类管理', 107 union all
select 112 ,'回收站管理', 107 union all
select 114 ,'团购管理', 108 union all
select 115 ,'拍卖管理', 108 union all
select 116 ,'优惠管理', 108 union all
select 117 ,'会员管理', 102 union all
select 118 ,'会员卡管理', 102 union all
select 119 ,'资金管理', 102 union all
select 120 ,'管理员管理', 102 union all
select 121 ,'添加管理员', 120 union all
select 122 ,'修改管理员', 120
go

--查所有子结点
if object_id('f_getC') is not null drop function f_getC
go
create function f_getC(@id int)
returns @re table(id int,level int,sort varchar(10))
as
begin
declare @l int
set @l=0
insert @re select @id,@l,null
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.modeid,@l,ltrim(isnull(b.sort,a.modeid)) from tb as a,@re as b
where b.id=a.parentid and b.level=@l-1
end
update @re set level = level -1
return
end
go

select a.modeid,a.parentid,REPLICATE('  ',b.level) +'┝'+a.modename,b.level,b.sort from tb  a,f_getC(0) b
where a.modeid=b.id
order by case when b.level<2 then 0 else 1 end,b.sort,b.level

/*
modeid      parentid                                                       sort       level
----------- ----------- -------------------------------------------------- ---------- -----------
100         0           ┝商品管理                                              100        0
107         100           ┝商品管理                                            100        1
108         100           ┝明细管理                                            100        1
109         100           ┝物流管理                                            100        1
101         0           ┝定单管理                                              101        0
102         0           ┝用户管理                                              102        0
117         102           ┝会员管理                                            102        1
118         102           ┝会员卡管理                                           102        1
119         102           ┝资金管理                                            102        1
120         102           ┝管理员管理                                           102        1
104         0           ┝学院广告                                              104        0
105         0           ┝系统设置                                              105        0
106         0           ┝附件管理                                              106        0
110         107             ┝商品信息管理                                        100        2
111         107             ┝商品分类管理                                        100        2
112         107             ┝回收站管理                                         100        2
114         108             ┝团购管理                                          100        2
115         108             ┝拍卖管理                                          100        2
116         108             ┝优惠管理                                          100        2
121         120             ┝添加管理员                                         102        2
122         120             ┝修改管理员                                         102        2

(所影响的行数为 21 行)

*/

--查所有子结点,带路径与排序
if object_id('f_getC') is not null drop function f_getC
go
create function f_getC(@id int)
returns @re table(id int,level int,sort varchar(100),path varchar(500))
as
begin
declare @l int
set @l=0
insert @re
select [modeid],@l,right('00000'+ltrim(modeid),5),modename
from tb where parentid=@id
while @@rowcount>0
begin
set @l=@l+1
insert @re
select a.modeid,@l,b.sort+right('00000'+ltrim(a.modeid),5),
b.path+' - '+a.modename
from tb as a,@re as b
where b.id=a.parentid and b.level=@l-1
end
update @re set level = level
return
end
go

select a.modeid,a.parentid,REPLICATE('  ',b.level) +'┝'+a.modename,b.level,b.sort ,b.path from tb  a,f_getC(0) b
where a.modeid=b.id
order by sort

/*
modeid      parentid                         level
----------- ----------- -------------------- ----------- -------------------- ----------------------------------------
100         0           ┝商品管理                0           00100                商品管理
107         100           ┝商品管理              1           0010000107           商品管理 - 商品管理
110         107             ┝商品信息管理          2           001000010700110      商品管理 - 商品管理 - 商品信息管理
111         107             ┝商品分类管理          2           001000010700111      商品管理 - 商品管理 - 商品分类管理
112         107             ┝回收站管理           2           001000010700112      商品管理 - 商品管理 - 回收站管理
108         100           ┝明细管理              1           0010000108           商品管理 - 明细管理
114         108             ┝团购管理            2           001000010800114      商品管理 - 明细管理 - 团购管理
115         108             ┝拍卖管理            2           001000010800115      商品管理 - 明细管理 - 拍卖管理
116         108             ┝优惠管理            2           001000010800116      商品管理 - 明细管理 - 优惠管理
109         100           ┝物流管理              1           0010000109           商品管理 - 物流管理
101         0           ┝定单管理                0           00101                定单管理
102         0           ┝用户管理                0           00102                用户管理
117         102           ┝会员管理              1           0010200117           用户管理 - 会员管理
118         102           ┝会员卡管理             1           0010200118           用户管理 - 会员卡管理
119         102           ┝资金管理              1           0010200119           用户管理 - 资金管理
120         102           ┝管理员管理             1           0010200120           用户管理 - 管理员管理
121         120             ┝添加管理员           2           001020012000121      用户管理 - 管理员管理 - 添加管理员
122         120             ┝修改管理员           2           001020012000122      用户管理 - 管理员管理 - 修改管理员
104         0           ┝学院广告                0           00104                学院广告
105         0           ┝系统设置                0           00105                系统设置
106         0           ┝附件管理                0           00106                附件管理

(21 行受影响)

*/

----------


还是这个脚本, SQL 2005 中的用法.


if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([modeid] int,modename varchar(20),parentid int)
insert [tb]
select 100 ,'商品管理', 0 union all
select 101 ,'定单管理', 0 union all
select 102 ,'用户管理', 0 union all
select 104 ,'学院广告', 0 union all
select 105 ,'系统设置', 0 union all
select 106 ,'附件管理', 0 union all
select 107 ,'商品管理', 100 union all
select 108 ,'明细管理', 100 union all
select 109 ,'物流管理', 100 union all
select 110 ,'商品信息管理', 107 union all
select 111 ,'商品分类管理', 107 union all
select 112 ,'回收站管理', 107 union all
select 114 ,'团购管理', 108 union all
select 115 ,'拍卖管理', 108 union all
select 116 ,'优惠管理', 108 union all
select 117 ,'会员管理', 102 union all
select 118 ,'会员卡管理', 102 union all
select 119 ,'资金管理', 102 union all
select 120 ,'管理员管理', 102 union all
select 121 ,'添加管理员', 120 union all
select 122 ,'修改管理员', 120
go

with
cr(modeid,modename,parentid,layer) as
(
select modeid,modename, parentid, cast( modeid as varchar) as layer from [tb]
where parentid = 0
union all
select tb.modeid,tb.modename,tb.parentid,cast(CAST( cr.layer as varchar) + cast(tb.modeid as varchar) as varchar) as layer
from tb
inner join cr
on tb.parentid = cr.modeid

)

select * from cr order by layer
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: