易截截图软件、单文件、免安装、纯绿色、仅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与Oracle、DB2的性能比较

开放性   SQL Server
  只能在Windows 上运行,没有丝毫的开放性,操作系统的系统的稳定对数据库是十分重要的。Windows9X系列产品是偏重于桌面应用,NT server只适合中小型企业。而且Windows平台的可靠性,安全性和伸缩性是非常有限的。它不象Unix那样久经考验,尤其是在处理大数据量的关键业务时。
  Oracle ......

sql 语句分类

sql 语句按功能分为3类:数据定义语句,数据操作语句,数据控制语句
一:数据定义语句:
       CREATE TABLE --创建一个数据库表
       DROP TABLE --从数据库中删除表
      ALTER TABLE --修改数据库表结构
  &n ......

sql server创建表

use test
go
if exists table student is not null
else
drop table student
go
create table  database_name.schema_name.table_name
(属性1  字符类型  约束,
属性2  字符类型  约束....
)
go
insert into table_name values ('属性1’,‘属性2’,......)
--插 ......

SQL日期时间不能早于1753年

SQL日期时间不能早于1753年
   
1.公元元年的第一天,也就是公元1年1月1日,那天是星期六。
    2.
现行的公历是格利戈里历法,这个历法并不是连续的,中间缺少了11天。1752年9月2日的后一天并不是9月3日,而是9月14日。也就是说,从1752年9月3日到9月13日的11天并不存在。
 &nb ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号