SQLSever触发器建立

来源:互联网 发布:苹果anywhere软件 编辑:程序博客网 时间:2024/06/06 08:55

先附上示例代码:

SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO-- =============================================-- Author:<Author,,Name>-- Create date: <Create Date,,>-- Description:<Description,,>-- =============================================CREATE TRIGGER  trigUserDelete   ON  userTable    instead of deleteAS BEGINdeclare @num varchar(20)    select @num=phoneNum from deleteddelete customRoute where userId=@numdelete userLocat where phoneNum=@numdelete userTable where phoneNum=@numENDGO

什么是触发器?在我的理解中:它不是人为启动的,而是系统自动启动的,就像事件一样,当触发条件满足时,就会执行触发器里面的内容。

在上述实例代码中,在表userTable中定义了一个名为trigUserDelete的删除(delete)触发器。

在我的数据库中有 customRoute,userLocat,userTable这三个表,前两表存在字段与userTable表中的phoneNum存在外键关系。现在要根据phoneNum来删除用户表(userTable)的内容。

userLocat(a,phoneNum):a为主键,phoneNum为外键(来自于userTable.phoneNum) 

 userTable(phoneNum,c,d) :phoneNum为主键 

 如果我把字段phoneNum的外键属性去掉,对编程没什么影响。 如果不去,userLocat中的phoneNum要么为空,要么是在userTable的phoneNum中存在的值。有外键的时候,数据库会自动帮你检查userLocat的phoneNum是否在UserTable的中存在。如果不存在,则操作失败。

所以,如果直接删除用户表中的用户,如果其他表的外键在该表的值中不存在,是会删除失败的。所以我们要删除用户表之前,需要删除其他表外键与之关联的数据。

类似的还有很多,例如现在有一个数据库,数据库中有两个表: 

博客表:(博客id,博客内容)

评论表:(评论id,评论内容,所属博客id); 其中所属博客id来自于 博客id。

  要想删除博客,在这之前要先删除所属这博客的评论  。


上述代码用的是INSTEAD OF触发器,和ALTER触发器不同的是,ALTER触发器在(delete,insert,update)原来操作后执行。而INSTEAD OF 是代替原来操作,也就是说不执行原来的SQL语句。 

触发器还用到了临时表,常用临时表有两个,一个是inserted ,还有一个是deleted。当用户做增删改操作时,会把将要插入的数据放入inserted中,同理会把将要删除的数据放在deleted中。

在一个实例代码:有这样的一个功能,用户能够上传自己位置,不过要把原来的位置删除。换言之,就是更新位置信息的操作。(注:userLocat(phoneNum,Latitude,Longitude)).

SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO-- =============================================-- Author:<Author,,Name>-- Create date: <Create Date,,>-- Description:<Description,,>-- =============================================CREATE TRIGGER  trigUserLocatInsert   ON  userLocat   instead of insertAS BEGINdeclare @phonenum varchar(20)declare @latitude floatdeclare @longitude floatselect @phonenum=phoneNum,@latitude=Latitude,@longitude=Longitude from inserteddelete userLocat where phoneNum=@phonenuminsert into userLocat (Latitude,Longitude,phoneNum) values(@latitude,@longitude,@phonenum)ENDGO

当然用update也可以实现。上述触发器在userLocat中定义,当进行insert操作的时候触发

原创粉丝点击