sql server 触发器求解!
需要写一个SQL触发器语句,如果我删除一个用户时,要求根据这个用户的ID删除A表 B表对应该用户的数据,同时根据这个用户的ID 删除另外6个数据库中A表 B表对应的数据,请问这个触发器该怎么写? SQL?Server 数据库 SQL
[解决办法]
说下大概思路,具体楼主百度触发器相关内容
1. 根据业务需求,决定触发器的类型 After?
2. 从deleted表中得到删除的用户
3. 删除相关表数据,如果相关表不在同一服务器,建立连接服务器,开启分布式事务
[解决办法]
举一个简单的例子
if (object_id('tgr_user_del', 'tr') is not null)
drop trigger tgr_user_del
GO
create tgr_user_del
on User
after delete
as
begin
declare @delcount int
set @delcount = 0
select @delcount = COUNT(*) from deleted
declare var_cursor cursor for
select UserId from deleted
open var_cursor
declare @userid int
while @delcount >0
begin
fetch next from var_cursor into @userid
delete * from tablea where tablea.userid = @userid
delete * from tableb where tableb.userid = @userid
--调用已经写好的存贮过程去传参数 删除其他数据库记录
set @delcount =@delcount - 1
end
close var_cursor
deallocate var_cursor
end
[解决办法]
create trigger [触发器名] on [表名]
after delete
as
begin
delete a
from A表 a
inner join deleted b on a.ID=b.ID
delete a
from B表 a
inner join deleted b on a.ID=b.ID
-- 删除另外6个数据库中A表 B表对应的数据
end