易截截图软件、单文件、免安装、纯绿色、仅160KB

SQL数据库CTE的用法

在很多编程语言中都有 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 中关于EXCEPT和INTERSECT的用法

熟练使用SQL Server中的各种用法会给查询带来很多方便。今天就介绍一下EXCEPT和INTERSECT。注意此语法仅在SQL Server 2005及以上版本支持。
EXCEPT是指在第一个集合中存在,但是不存在于第二个集合中的数据。
INTERSECT是指在两个集合中都存在的数据。
测试如下:
create table t1(id int,mark char(2))
go
create ta ......

SQL Server 索引结构及其使用(一)

SQL Server 索引结构及其使用(一)
作者:freedk
一、深入浅出理解索引结构
  实际上,您可以把索引理解为一种特殊的目录。微软的SQL SERVER提供了两种索引:聚集索引(clustered index,也称聚类索引、簇集索引)和非聚集索引(nonclustered index,也称非聚类索引、非簇集索引)。下面,我们举例来说明一下聚集索 ......

SQL Server 索引结构及其使用(三)

SQL Server 索引结构及其使用(三)
作者:freedk
一、深入浅出理解索引结构
二、改善SQL语句
实现小数据量和海量数据的通用分页显示存储过程
  建立一个 Web 应用,分页浏览功能必不可少。这个问题是数据库处理中十分常见的问题。经典的数据分页方法是:ADO 纪录集分页法,也就是利用ADO自带的分页功能(利用游 ......

SQl Code表设计

在Asp.net后有很多常用的表结构 membership就是一个典型,除此还有code表
CREATE TABLE [dbo].[CodeTables](
    [CodeTableID] [uniqueidentifier] NOT NULL,
    [ParentCodeTableID] [uniqueidentifier] NULL,
    [Name] [varchar](200) COLLATE SQL_Latin1_General_ ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号