SQL数据库怎么进行多表级联更新,求个存储过程

SQL数据库怎么进行多表级联更新,求个存储过程,第1张

方法、过程如下:

在每个数据库的table1\table2都建立插入、删除、修改触发器

如在A1上

ceate trigger dbo.table1_u on A1.dbo.table1 for insert,update,delete as

IF @@rowcount = 0 RETURN

declare @no_i int -- 假设no为关键字

--declare 其他字段

declare @no_d int -- 假设no为关键字

--declare 其他字段

--赋值

select @no_i =no ,--其他值

from inserted

select @no_d =no ,--其他值

from deleted

--判断@no_d,@no_i 是否在A2,A3,A4,A5的表中存在

--1、如果@no_d,@no_i 都存在,则用新值更新A2,A3,A4,A5的talbe1

--2、如果@no_d不存在@no_i存在,则将新值插入A2,A3,A4,A5的talbe1

--3、如果@no_d存在@no_i不存在,则删除A2,A3,A4,A5的talbe1对应的值

if exists(select 1 from A2.dbo.talbe1 where no = @no_d) and

exists(select 1 from A2.dbo.talbe1 where no = @no_i)

begin

--修改A2数据库的表

end

--你要先在测试库测试哦

--建表

create table t_bd_item_info

(

    item_no Varchar(20),

    item_subno Varchar(20)

)

--测试数据

insert into t_bd_item_info values('12345678','98765432')

insert into t_bd_item_info values('123456789012','12345678')

insert into t_bd_item_info values('1234567801234','98976543')

--得到需要替换的item_no和item_subno

Select * into #Tmp From 

(

    Select *,ROW_NUMBER() over(partition by item_subno order by item_no) As id 

    From t_bd_item_info A

    Where len(item_no) in(12,13) and LEN(item_subno)=8

    And not exists(Select * From t_bd_item_info B where B.item_no=A.item_subno)

) S where ID=1

--替换(包含item_no的所有表都替换)

Exec sp_MSforeachtable @command1="Update ? Set item_no=B.item_subno From ? A inner join #Tmp B on A.item_no=B.item_no",@whereand=" And o.name in (select distinct object_name(object_id) from sys.columns where name='item_no')"

--删除临时表

Drop Table #Tmp


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/10862989.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-11
下一篇2023-05-11

发表评论

登录后才能评论

评论列表(0条)

    保存