当添加/更新在另一个表中发生时,如何通过SQL Server中的存储过程在表中添加/更新记录

时间:2019-01-30 01:29:14

标签: sql sql-server stored-procedures

我有一个如下所述的表格

主表:

id, application, type
1, ram, good
2, ramesh, average
3, suresh, good

辅助表

application_s, rank
ram, 2
ramesh, 4
suresh,1

现在,该方案是在主表中将“ ram”应用程序替换为“ Ramarajan”,将“ Suresh”替换为“ Suresh kumar”。

如何使用存储过程或任何存储过程在SQL Server中进行上述更新?

1 个答案:

答案 0 :(得分:0)

一种解决方案是在主表上创建一个触发器,其触发方式如下:

  • 当主表已UPDATE d并且application被更改时,它也在辅助表中也被更改
  • 从主表中DELETE记录时,将删除辅助表中具有相同应用程序的相应记录
  • 将新记录INSERT插入主表时,新记录也会插入到辅助表中(其他列为空)。

代码:

create trigger maintable_trigger
on maintable
after UPDATE, INSERT, DELETE
as
    if exists(select * from inserted) and exists (SELECT * from deleted)     --update
    begin
        update s 
        set s.application_s = i.application
        from secondarytable s
        inner join deleted d on d.application = s.application_s
        cross join inserted i;
    end

    if exists (select * from inserted) and not exists(Select * from deleted) --insert
    begin
        insert into secondarytable select i.application, null from inserted i;
    end

    if exists(select * from deleted) and not exists(Select * from inserted)  --delete 
    begin
        delete from secondarytable
        where exists (
            select 1 from deleted d where d.application = secondarytable.application_s
        )
    end

See it in action in this DB Fiddle