【问题标题】:SQL Trigger to update a field on insert if the inserted value conflicts with the unique constraint如果插入的值与唯一约束冲突,则 SQL 触发器在插入时更新字段
【发布时间】:2011-04-09 11:56:06
【问题描述】:

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

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

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

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

感谢您的帮助!

【问题讨论】:

    标签: sql sql-server sql-server-2008 triggers


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多