在很多编程语言中都有 for循环这样的东西。在数据库里面 替代他是 游标
但是游标使用起来是相当耗费资源的,今天看见一个CTE尝试了下他的用法
create table employewhere
(
id int identity(1,1),
[name] varchar(10),
[value] varchar(10),
[ttime] int
)
insert employewhere
select '张三',2,1
union all
select '张三',2,2
union all
select '张三',2,3
union all
select '张三',2,4
union all
select '李四',2,1
union all
select '李四',2,2
union all
select '李四',2,3
union all
select '李四',2,4
union all
select '李四',2,1
insert employewhere
select '王五',2,1
union all
select '王五',2,3
union all
select '王五',2,4
我想得到ttime为连续数字的name
张三
李四
select * from employewhere
1 张三 2 1
2 张三 2 2
3 张三 2 3
4 张三 2 4
5 李四 2 1
6 李四 2 2
7 李四 2 3
8 李四 2 4
9 王五 2 1
10 王五 2 3
11 王五 2 4
12 王五 2 1
13 王五 2 3
14 王五 2 4
15 王五 2 1
16 王五 2 3
17 王五 2 4
-----------------------------
with myCTE as
(
select id,[name],value,ttime ,1 as number from employewhere where value=2
union all
select tt.id,tt.name,tt.value,tt.ttime ,number+1 from employewhere as tt
inner join myCTE on myCTE.[name]=tt.[name] and tt.ttime=myCTE.ttime+1--连接起来的条件
where tt.value=2
)
select * from myCTE where number>3
8 李四 2 4 4
4 张三 2 4 4
但是为什么要这么写呢
我们可以这么执行查询里面的数据
with myCTE as
(
select id,[name],value,ttime ,1 as number from employewhere where value=2
union all
select tt.id,tt.name,tt.value,tt.ttime ,number+1 from employewhere as tt
inner join myCTE on myCTE.[name]=tt.[name] and tt.ttime=myCTE
客户反映程序很慢,开始以为数据量大,在表中查询使用的字段上,添加了索引,没有明显的效果,检查时发现以前的同事在sql server中写的函数中使用了in,而在in的结果集中会有2500条记录左右,执行时间需要13秒。找到问题根源,
修改方法: 把in后面的子查询作为一个表和主表关联,添加限制条件。
原来写法: select * fro ......