我有一个名为Albums的表,其中包含一个字段IsDeleted和一个字段“Name”。 名称是唯一键。我的问题是:
如果设置为True并且用户将相同的名称插入表中,是否可以创建将IsDeleted更新为False的触发器?
当然,insert语句应该以某种方式更改为更新语句。
我正在使用MSSQL 2008,我对触发器和SQL ingeneral
非常新感谢您的帮助!
答案 0 :(得分:2)
是的,您可以使用instead of
触发器执行此操作。例如:
create trigger albums_ins_trig on albums instead of insert as begin
-- update albums which already exist and are being inserted again
update albums set IsDeleted=0 where IsDeleted=1
and exists (select * from inserted where albums.name=inserted.name)
-- insert new albums
insert into albums select * from inserted
where not exists (select * from albums where albums.id=inserted.id)
end