数据库索引,存储过程,视图,事务

一,索引
索引是一个独立的,物理的数据库结构,可以快速找到表或视图的信息
通常情况下只有需要经常查询索引列中的数据时才在表上创建索引
基本语法:
CREATE INDEX StockIndex
ON appSchema.StockEvents (StockSymbol);
创建唯一索引:
Create unique index 索引名称
On 表名(字段1,字段2)
聚集索引:clustered 每个键值只有一个聚集索引
非聚集索引noclustered:索引的键值包含指向表中记录存储位置的指针,不对表中数据排序
聚集索引的创建:
Create unique clustered  index 索引名称
On 表名(字段名 DESC)
非聚集函数:
Create unique nonclustered  index 索引名称
On 表名(字段名)
两种非聚集索引:建于堆上和建于聚集索引上
查询索引:exec sp_helpindex 表名
删除索引:drop index 表名.索引名
二,视图:
视图是一种逻辑对象,它是从一个或几个基本表中导出来的表,是一种虚拟表。
视图的内容可以是:1,基表中列的子集或行的子集 2,两个或多个基表的联合 3,基表的统计汇总 4,其他视图的子集 5,视图和基表的混合 
视图定义的限制:1, create view语句不能包括compute或comprte by子句,也不能包括into关键字 2,仅当使用top关键字时,create view语句才能包括order by子句
3,视图不能引用临时表 4,视图不能引用超过1024列 5,在单一批处理中create view语句不能和其他t—sql语句组合使用
创建视图:
create view v_uservip
as
select [user].userid,[user].username,vipid,vipdate from [user] join vip
on [user].userid=vip.userid
更改视图:
alter view v_uservip
as
select [user].userid,sex,[user].username,vipid,vipdate from [user] join vip
on [user].userid=vip.userid
删除视图
drop view dbo.v_uservip
使用索引视图
1, 视图上创建的第一个索引必须是唯一聚集索引2, 创建视图时必须使用schemabinging选项 3,视图可以引用基表,但不能引用其他视图4,引用表和用户定义函数的时候,必须使用两部分名称 5,随后使用索引图的连接必须具有相同的选项设置。
2, 创建索引视图的限制
视图上创建的第一个索引必须是惟一聚集索引
创建视图时必须使用 SCHEMABINDING 选项
视图可以引用基表,但不能引用其他视图
引用表和用户定义函数的时候,必须使用两部分名称
随后使用索引视图的连接必须具有相同的选项设置
三,事务
事务可以自动提交或回滚,当事务中的一条语句不能执行则事务中的其他语句都不能执行
每条单独的语句都是一个事务
begin transaction    事务的起始点
begin try
insert into stu values('Jack1',20,1)
insert into stu values('Jack2',2,1)
commit transaction  事务提交
end try
begin catch
print '错误'
rollback transaction   事务回滚
end catch
select * from stu
四,存储过程
存储过程是一组为了完成特定功能的sql语句集,经编译后存储在数据库中,存储过程可包含程序流、逻辑以及对数据库的查询。他们可以接受参数、输出参数、返回单个或多个结果集以及返回值
if……else语句
 use pubs

declare @pic float
select @pic=sum(price) from  titles
if @pic>500
begin
print 'more 500'
end
else
begin
print 'less 500'
end
case条件:
use northwind
go
select top 10 orderid,orderid %10 as 'Last Digit',Position=
Case orderid %10
 when 1 then 'First'
 when 2 then 'Second'
 when 3 then 'Third'
 when 4 then 'Fourth'
Else 'Something Else'
end 
from orders
whil循环:
declare @i int
set @i=1 
while @i<10
begin 
print @i
set @i=@i+1
end
waitfor语句:
Waitfor
Delay  ‘01:00’  --等待一小时后执行
Print ‘SQL’

Waitfor
Time ’08:30’  --等待到8点30分执行操作
Pint ‘SQL’
创建有参数的存储过程:
use pubs
go
create procedure MyPRO
@id varchar(11),
@contract bit,
@phone char(12) output
as
select @phone=phone from authors where au_id=@id and [contract]=@contract

--调用存储过程
decla @phone char(12)
exec mypro '267-41-2394',true,@phone output
print @phone


sql中获得随机数的方法为:newid()

对网上看到的compute和compute by例子的理解:
sqlserver中可以使用sum()和group by对查询的字段进行分组并获得总和,但是只会返回总和而不能得到详细信息,compute可以得到所有数据的详细信息并在最后得到总和
USE pubs
SELECT type, price, advance
FROM titles
ORDER BY type
COMPUTE SUM(price), SUM(advance)
compute by只能与order by同时出现,按组把各个数据列出,并计算出各个组的和
USE pubs
SELECT type, price, advance
FROM titles
ORDER BY type
COMPUTE SUM(price), SUM(advance) BY type

猜你喜欢

转载自blog.csdn.net/qq_25824243/article/details/73458005