SQLserver的事务,索引,视图,函数,存储过程

来源:互联网 发布:现代通信网络试题答案 编辑:程序博客网 时间:2024/05/20 17:10
一.事务
     在sqlserver中当出现多条语句时,当其中有一条不合理,不会停止下来,
     因此,我们会用事务去解决这个问题,当有一个错误时,不允许往下继续进行,
    只有当全部正确时,才给予通过。
    事务开启:begin transaction
    有错误时回滚事务: rollback
    提交事务:commit
    在这里我们需要创建一个错误的总和变量@eSum
    每次更新插入数据时需要@eSum = + @@error
    当@eSum的值不为0,说明又错误,需要rollback
    否则。commit提交事务
   
二. 索引
    
--索引的创建和使用
if exists (select * from sysindexes where name = 'index_tage')
drop index student.index_tage
go
 
create nonclustered index index_tage on student(id)--非聚集索引,聚集索引一般是主键或者有唯一约束的列
with fillfactor = 1--填充因子
go
 
select * from ALL_PURPOSE_CARD with (index = index_tage)
go

三.视图
--视图的创建(可做权限控制)
if exists (select * from sysobjects where name = 'v_student_msg')
drop view v_student_msg
go
create view v_student_msg
as
select * from student where id =4
go
--视图的使用
select * from v_student_msg
--视图虽然是虚拟表,但是可以更新数据
update v_student_msg set goSchool = GETDATE()
--select * from v_student_msg
go

四.函数
sql 函数中分为标量值函数,表值函数.
标量值函数:参数有一个或者多个,结果返回单一的值
表值函数: 返回一个表数据

--标量值函数
if exists (select * from sysobjects where name = 'getStudentName')
drop function getStudentName
go
 
create function getStudentName(
@Student_id int
)
returns nvarchar(10)
as
begin
declare @Student_name nvarchar(10)
select @Student_name = ACCOUNT_NAME from ACCOUNT where Student_ID = @Student_id
return @Student_name
end
go
--select dbo.getStudentName(1)
print dbo.getStudentName(1)
go

--表值函数
if exists (select * from sysobjects where name = 'getStudentMsg')
drop function getStudentMsg
go
create function getStudentMsg(@sc float)
returns @Student_score table(
StudentName nvarchar(10),
score float
)
as
begin
insert into @Student_score
select s.Student_NAME,sc.Score from Student s inner join Score sc on a.Student_ID = sc.Student_ID
where sc.Score >@sc
return
end
go
 
 
select * from dbo.getAccInfo(80)

    
--内联表值函数
if exists (select * from sysobjects where name = 'getStudentMsg')
drop function getStudentMsg
go
create function getStudentMsg(@sc float)
returns table
 
begin
return ( select s.Student_NAME,sc.Score from Student s inner join Score sc on a.Student_ID = sc.Student_ID
where sc.Score >@sc )
end
go
select * from dbo.getAccInfo(80)

五.存储过程(procedure)
     存储过程有自定义存储过程,有内置的存储过程,内置的存储过程是以sp_开头的。
     
use School(库名)
go
--自定义
if exists (select * from sysobjects where name = 'ups_getStudentName')
drop proc ups_getStudentName
go
 
create proc ups_getStudentName
@id int,
@score int
as
select name from Student where id = @id and score = @score
go
--存储过程的使用,关键字exce
exce ups_getStudentName '2','70'
use School(库名)
go
--自定义存储过程
--带有输出参数的存储过程
if exists (select * from sysobjects where name = 'ups_getStudentName')
drop proc ups_getStudentName
go
create proc ups_getStudentName
@id int,
@score int output
as
select @score=Student_score from Student where Student_id = @id
go
--存储过程的使用,关键字exce
--带有输出参数的存储过程,在打印的时候需要先定义一个变量接收
declare @Studentscoce int
exce ups_getStudentName '1',@Studentscoce
print '学号是1的学生分数是:'+@Studentscoce


1 0