SQL WITH AS

SQL中 WITH AS 的用法和注意事项

1.为什么使用with as

我们在使用sql语句的时候经常使用子查询,但是子查询占用系统的资源是很多了,如果用在了循环中更是可怕,当然我们可以使用表量函数,但是标量函数的成本还是否不小,所以sql2005给我们提供了一个表达式 with as

使用with as应该注意

1 with as后面必须紧跟使用CTE(Common table Express) (with as)的语句

with  a as

(

select * from tb1

)

select * from tb2,a where a.id=tb1.id

2 多个CTE 之间加,分割

with t1 as

(

select * from t1

),

t2 as

(

select * from t2

),

t3 as

(

select * from t3

)

3 如果CTE 和某个表重名则第一个使用cte 后面的就是使用了表

--table1 数据库中有table1

with table1 as

(

select * from tb1

)

select * from tb2,table1 where tb1.id=table1.id  --CTE

select * from tb2,table1 where tb1.id=table1.id  --table1

4 如果CTE属于批处理的一部分,那么用;和批处理分割

declare @t1 int

set @t1=2

;

with t as

(

select * from table1

)

select * from tb2 ,t where tb2.id=t.id

今天又学到了With

With 除了有上面提到的功能以为,With 还有以下的功能

1  递归调用

  假如,有一个父子关系的表结构,就拿员工表吧,EmployeeID,ReportTO ,FirstName,LastName,其中ReportTO保存着当前记录的直接上级

那么我们怎么才能查询出给定一个人的下级(所有下级),答案是使用With递归

with Emp as

(

  select EmployeeID,ReportTo,FirstName,LastName

  from Employees where Employee=4

  Join All

  select emp.EmployeeID,emp.ReportTo,emp.FirstName,emp.LastName

  from Employees emp

  join Emp

  on Emp.EmployeeID=emp.ReportTo

)

select * from Emp

在With中第一个是锚点,就是从那里开始,第二个循环是递归的主体,知道查询结果为空就结束,这样我们就实现了我们的要求了

原文地址:https://www.cnblogs.com/yunfeiqi/p/2728228.html