首页 > 代码库 > 2014-12-04 视图、触发器

2014-12-04 视图、触发器

视图:把一个查询结果集当作表

例:select * from (select * from score,grade where score.degree between low and upp) as jieguotable

     where rank=‘A‘

    as 后面的作为一个虚拟的表

create view shitu1

as

select * from student,score where student.sno=score.sno

go

as 和 go 之间实际为表连接,表里的列不能重合

视图只能查询使用,不能增删数据,相当于存了一条数据进去   

 

触发器:一个特殊的存储过程,通过增删数据库来引发。

鼠标操作:某个数据库→可编程性→数据库触发器

例:create trigger TR_student_Insert   ---(命名规则:TR为触发器,student为哪个表,insert为新增操作时触发)

     on student  ---作用于哪个表

     for insert ------for是新增之后触发,for还可以写成after

     as

     begin

     select * from student

     end

     go

     insert into student values(‘303‘,‘小明‘,‘男‘,‘1992-07-21‘,‘95033‘)

   -----在增加完以上一条数据后,触发查询

 

替换:

create trigger TR_Student_Delete
on student
instead of delete
as
begin
 declare @sno int
 select @sno=sno From deleted
 delete from score where sno=@sno
 delete from student where sno=@sno
end
go
delete from Student where Sno=304
select *from student
insert into Score values(304,‘3-105‘,98)

deleted 为临时删除的内容,包含你将要执行的删除操作的内容

insert为临时增加

 

create trigger TR_student_inserted
on student
instead of insert
as
begin
 declare @sno int,@sname varchar(20),@ssex varchar(20),
 @sbirthday datetime, @class varchar(20)
 select @sno=sno,@sname=sname,@ssex=ssex,@sbirthday=sbirthday,@class=class from inserted
 if @ssex=‘男‘
 begin
  set @ssex=‘1‘
 end
 insert into student values(@sno,@sname,@ssex,@sbirthday,@class)
end
go
insert into student values(303,‘金拓‘,‘男‘,‘1992-07-21‘,‘95033‘)
select *from student

2014-12-04 视图、触发器