我有一个如下所述的表格
主表:
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中进行上述更新?
答案 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