触发器

     一:触发器是一种特殊的存储过程﹐它不能被显式地调用﹐而是在往表中插入记录﹑更新记录或者删除记录时被自动地激活。所以触发器可以用来实现对表实施复杂的完整性约`束。

    二:SQL Server为每个触发器都创建了两个专用表﹕Inserted表和Deleted表。这两个表。

    三: Deleted表存放由于执行Delete或Update语句而要从表中删除的所有行。
    四: Inserted表存放由于执行Insert或Update语句而要向表中插入的所有行。

    五: 使用T-SQL语句来创建触发器

基本语句如下﹕       
           create trigger trigger_name
           on {table_name | view_name}
           {for | After | Instead of }
           [ insert, update,delete ]
           as
           sql_statement

六﹕删除触发器:

基本语句如下﹕

     drop trigger trigger_name

七:查看数据库中已有触发器:

-- 查看数据库已有触发器
use jxcSoftware
go
select * from sysobjects where xtype='TR'

-- 查看单个触发器
exec sp_helptext '触发器名'

八﹕修改触发器:

基本语句如下﹕       
            alter trigger trigger_name
           on {table_name | view_name}
           {for | After | Instead of }
           [ insert, update,delete ]
           as
           sql_statement
         
九﹕相关示例﹕        
1﹕在Orders表中建立触发器﹐当向Orders表中插入一条订单记录时﹐检查goods表的货品状态status是否为1(正在整理)﹐是﹐则不能往Orders表加入该订单。
create trigger orderinsert
on orders
after insert
as
if (select status from goods,inserted
where goods.name=inserted.goodsname)=1
begin
print 'the goods is being processed'
print 'the order cannot be committed'
rollback transaction   --回滚﹐避免加入
end
2﹕在Orders表建立一个插入触发器﹐在添加一条订单时﹐减少Goods表相应的货品记录中的库存。
create trigger orderinsert1
on orders
after insert
as
update goods set storage=storage-inserted.quantity
from goods,inserted
where
goods.name=inserted.goodsname
3﹕在Goods表建立删除触发器﹐实现Goods表和Orders表的级联删除。
create trigger goodsdelete
on goods
after delete
as
delete from orders
where goodsname in
(select name from deleted)
4﹕在Orders表建立一个更新触发器﹐监视Orders表的订单日期(OrderDate)列﹐使其不能手工修改.
create trigger orderdateupdate
on orders
after update
as
if update(orderdate)
begin
raiserror(' orderdate cannot be modified',10,1)
rollback transaction
end
5﹕在Orders表建立一个插入触发器﹐保证向Orders表插入的货品名必须要在Goods表中一定存在。
create trigger orderinsert3
on orders
after insert
as
if (select count(*) from goods,inserted where goods.name=inserted.goodsname)=0
begin
print ' no entry in goods for this order'
rollback transaction
end

6:Orders表建立一个插入触发器,保证向Orders表插入的货品信息要在Order表中添加

alter trigger addOrder
on Orders
for insert
as
insert into Order
select inserted.Id, inserted.goodName,inserted.Number from inserted

posted @ 2013-07-16 16:47  New~one  阅读(203)  评论(0编辑  收藏  举报