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
相关文档:
1:exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '192.168.*.12'
exec sp_addlinkedsrvlogin 'ITSV ', 'false ',null, 'sa ', 'F00000'
2:
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', ......
SQL Server 索引结构及其使用(二)
作者:freedk
一、深入浅出理解索引结构
改善SQL语句
很多人不知道SQL语句在SQL SERVER中是如何执行的,他们担心自己所写的SQL语句会被SQL SERVER误解。比如:
select * from table1 where name=''zhangsan'' and tID > 10000
和执行:
select * from table1 where tID ......
1.create database dataname
这是创建数据库最简单的方法.数据库的各个属性都是默认.如数据库文件与日志文件存储目录.数据库大小等.
下面介绍下常用决定数据库属性的子句.
on:简单理解为定义存储数据库文件的位置,看下面代码.
filename:数据库的逻辑别名
size:数据库初始大小
maxsize:数据库初大容量
fil ......
sql 语句按功能分为3类:数据定义语句,数据操作语句,数据控制语句
一:数据定义语句:
CREATE TABLE --创建一个数据库表
DROP TABLE --从数据库中删除表
ALTER TABLE --修改数据库表结构
&n ......
use master
go
--切换master数据库
if exists(select 1 from sysdatabases where name = N'test')
--注意该同名数据库是否还要用到
begin
drop database test
end
go
create database test
on
primary
( name = 'testprimary', --主数据文件逻辑名
filename = 'D:\testprimary.mdf',--主数据文件存放路径
......