如果插入的值与唯一约束冲突,则 SQL 触发器在插入时更新字段

发布于 2024-10-31 21:09:53 字数 236 浏览 0 评论 0原文

我有一个名为相册的表,其中包含一个字段 IsDeleted 和一个字段“名称”。 名称是唯一的键。我的问题是:

如果将 IsDeleted 设置为 True 并且用户将相同的名称插入到表中,我是否可以创建一个将 IsDeleted 更新为 False 的触发器?

当然,插入语句应该以某种方式更改为更新语句。

我正在使用 MSSQL 2008,我对触发器和 SQL 非常陌生,

感谢您的帮助!

I have a Table called Albums which contains a field IsDeleted and a field "Name".
Name is a unique key. My Question is:

Can I create a trigger which updates IsDeleted to False if it is set to True and the same name is inserted into the table by the user?

Of course the insert statement should somehow be changed to an update statement.

I'm Using MSSQL 2008 and I'm very new to triggers and SQL ingeneral

Thanks for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼眸里的快感 2024-11-07 21:09:53

是的,您可以使用 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

Yes, you can do this with an instead of trigger. Example:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文