如何创建触发器,限制删除或修改记录
有两个表 A, B
A 表含有字段 ID
B 表含有字段 A_ID(数据来源就是A的ID)
如何给A表创建一个触发器,当要删除或修改A表记录时,判别B表A_ID是否使用了A表的ID,如果使用了该ID,就不允许A表修改或删除该ID的记录。
我是菜鸟,望各位大佬帮帮。
谢谢!
[解决办法]
create trigge dbo.a_U_b on dbo.a for update,delete
as
--update,delete
if exists(select 1 from b join deleted a on a.id=b.id)
begin
rollback tran
raiserror('不能修改,删除记录',16,1)
return
end
if OBJECT_ID('b') is not null
drop table b
go
if OBJECT_ID('a') is not null
drop table a
go
create table a(id int primary key,v varchar(10) )
insert into a
select 1,'aa' union all
select 2,'111'
create table b(
id int ,a_id int ,vv varchar(10)
)
insert into b
values(2,1,'bb')
go
create trigger dbo.trigger_a
on a
for delete,update
as
if exists(select *
from deleted d
inner join b
on b.a_id= d.id )
rollback
go
--不能删除
delete from a where id = 1
/*
消息 3609,级别 16,状态 1,第 1 行
事务在触发器中结束。批处理已中止。
*/
--不能修改
update a
set v = 'xxx'
where id= 1
/*
消息 3609,级别 16,状态 1,第 1 行
事务在触发器中结束。批处理已中止。
*/
--id 为2的可以修改,可以删除
update a
set v = 'xxx'
where id= 2
delete from a where id = 2
create table A表
(ID int,descr varchar(10))
insert into A表
select 1,'xxx' union all
select 2,'yyy'
create table B表
(A_ID int,b1 varchar(10),b2 varchar(10))
insert into B表
select 2,'aaaa','bbbb'
-- 建触发器
create trigger tr_tablea on A表
for update,delete
as
begin
if exists(select 1 from inserted a,B表 b where a.ID=b.A_ID)
or exists(select 1 from deleted a,B表 b where a.ID=b.A_ID)
begin
raiserror('ID在B表已使用,不允许修改或删除.',16,1)
rollback transaction
end
end
-- 测试删除ID 2
delete from A表 where ID=2
/*
Msg 50000, Level 16, State 1, Procedure tr_tablea, Line 9
ID在B表已使用,不允许修改或删除.
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
*/
-- 测试修改ID 2
update A表 set descr='aaa' where ID=2
/*
Msg 50000, Level 16, State 1, Procedure tr_tablea, Line 9
ID在B表已使用,不允许修改或删除.
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
*/
-- 测试修改ID 1
update A表 set descr='aaa' where ID=1
/*
(1 row(s) affected)
*/
-- 结果
select * from A表
/*
ID descr
----------- ----------
1 aaa
2 yyy
(2 row(s) affected)
*/