微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何防止触发触发器,以使重复数据不会输入到表中

如何解决如何防止触发触发器,以使重复数据不会输入到表中

假设我有3张这样的桌子:

authorGenres (authorGenreId,authorId,isPublished)

bookLibrarys (bookLibraryId,authorGenreId,bookId)

bookList (bookId,authorId)

我创建了一个触发器,当在authorGenres中更新一行并将isPublished列设置为1时触发。

发生这种情况时,触发器会将行插入bookLibrarys表中,其中authorGenreId列设置为在authorGenres中更新的行

这是我的工作触发器:

ALTER TRIGGER [dbo].[setCorrectGenreAfterUpdate]
   ON  [dbo].[authorGenres]
   AFTER UPDATE
AS 
BEGIN
    SET NOCOUNT ON;
    DECLARE @bookID AS NVARCHAR(50);
    DECLARE @bookLibraryId AS UNIQUEIDENTIFIER;
    DECLARE @author IDUNIQUEIDENTIFIER;
    SELECT @authorID = Inserted.authorID FROM inserted;

    SET @bookLibraryId = NEWID(); 
    SET @bookID = ( SELECT bookId 
                    FROM booklist nl 
                    WHERE nl.authorID = @authorID)

    INSERT INTO booklibrarys(bookLibraryID,parentBookID,genreID)
    SELECT @bookLibraryId,@bookID,genreID FROM Inserted

END

当我像这样UPDATE dbo.authorGenres SET isPublished = 1 WHERE genreID = 'C325061D-4274-487B-93F9-03BEB8B7D4D5'进行测试更新时,它会工作并将新行插入bookLibrarys中。

问题是,如果我再次进行更新,则会在bookLibrarys中获得另一个新行,该行具有相同的authorGenreId和bookId,但是有一个新的bookLibraryId,因为这是在触发器中生成的。

是否只有在bookLibrarys中不存在具有bookId和authorGenreId的行时才使触发器运行?

谢谢!

解决方法

尝试使用LEFT JOIN来检查是否已经存在相同的记录,并确保具有@Lamu在注释中建议您的代码可以在多行上使用。

类似这样的东西:

ALTER TRIGGER [dbo].[setCorrectGenreAfterUpdate]
   ON  [dbo].[authorGenres]
   AFTER UPDATE
AS 
BEGIN
    SET NOCOUNT ON;

    INSERT INTO booklibrarys(bookLibraryID,parentBookID,genreID)
    SELECT NEWID(),bl.bookId,ins.genreID FROM Inserted ins
    INNER JOIN booklist bl ON bl.authorID = ins.authorID -- this is to get  bookId for each row,not for one like in variable
    LEFT JOIN booklibrarys blib ON blib.genreID = ins.genreID AND bl.bookId = 
blib.parentBookID
    WHERE blib.bookLibraryID is NULL
END

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。