视图
T-SQL with as 的用法 SQL 下的递归查询 SQL2005(CTE) ,SQL2000(Function 递归)
2017-02-20 13:12:10

作者: 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[ ,n ] ]::=        expression_name [ ( column_name [ ,n ] ) ]    AS        ( CTE_query_definition )

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

withcr 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:

withcr 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语句所示:

withcte1 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是一个实际存在的表

withtable1 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%';  -- 必须加分号witht_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]gocreate table [tb]([modeid] int,modename varchar(20),parentid int)insert [tb]select 100 ,'商品管理', 0 union allselect 101 ,'定单管理', 0 union allselect 102 ,'用户管理', 0 union allselect 104 ,'学院广告', 0 union allselect 105 ,'系统设置', 0 union allselect 106 ,'附件管理', 0 union allselect 107 ,'商品管理', 100 union allselect 108 ,'明细管理', 100 union allselect 109 ,'物流管理', 100 union allselect 110 ,'商品信息管理', 107 union allselect 111 ,'商品分类管理', 107 union allselect 112 ,'回收站管理', 107 union allselect 114 ,'团购管理', 108 union allselect 115 ,'拍卖管理', 108 union allselect 116 ,'优惠管理', 108 union allselect 117 ,'会员管理', 102 union allselect 118 ,'会员卡管理', 102 union allselect 119 ,'资金管理', 102 union allselect 120 ,'管理员管理', 102 union allselect 121 ,'添加管理员', 120 union allselect 122 ,'修改管理员', 120go    --查所有子结点if object_id('f_getC') is not null drop function f_getCgocreate 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.level0     begin          set @l=@l+1         insert @re   select a.modeid,@l,b.sort+right('00000'+ltrim(a.modeid),5), b.path+' - '+a.modenamefrom 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  /*modeidparentid 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]gocreate table [tb]([modeid] int,modename varchar(20),parentid int)insert [tb]select 100 ,'商品管理', 0 union allselect 101 ,'定单管理', 0 union allselect 102 ,'用户管理', 0 union allselect 104 ,'学院广告', 0 union allselect 105 ,'系统设置', 0 union allselect 106 ,'附件管理', 0 union allselect 107 ,'商品管理', 100 union allselect 108 ,'明细管理', 100 union allselect 109 ,'物流管理', 100 union allselect 110 ,'商品信息管理', 107 union allselect 111 ,'商品分类管理', 107 union allselect 112 ,'回收站管理', 107 union allselect 114 ,'团购管理', 108 union allselect 115 ,'拍卖管理', 108 union allselect 116 ,'优惠管理', 108 union allselect 117 ,'会员管理', 102 union allselect 118 ,'会员卡管理', 102 union allselect 119 ,'资金管理', 102 union allselect 120 ,'管理员管理', 102 union allselect 121 ,'添加管理员', 120 union allselect 122 ,'修改管理员', 120go

 modeid,modename, parentid, ( modeid  )  layer            parentid              tb.modeid,tb.modename,tb.parentid,(( cr.layer  )  (tb.modeid  )  )   tb.parentid    cr   layer