0

我有以下触发器,当在主表中更新条目时,它应该在联结表中插入记录。但是这个触发器没有触发(它之前触发过)

CREATE TRIGGER [dbo].[trUpdateRegistrant]
ON [dbo].[hr_Registrants]
FOR UPDATE  
AS

DECLARE @RegistrantID INT, @CategoriesIDs VARCHAR(1000), @DesiredCategoriesIDs VARCHAR(1000), @LanguagesIDs VARCHAR(1000), 
    @CategoryIDsChanged BIT, @DesiredCategoriesIDsChanged BIT, @LanguagesIDsChanged BIT

DECLARE curRegs CURSOR FOR
SELECT I.RegistrantID, 
    I.CategoriesIDs, 
    I.DesiredCategoriesIDs, 
    I.LanguagesIDs,
    CASE WHEN D.CategoriesIDs <> I.CategoriesIDs THEN 1 ELSE 0 END,
    CASE WHEN D.DesiredCategoriesIDs <> I.DesiredCategoriesIDs THEN 1 ELSE 0 END,
    CASE WHEN D.LanguagesIDs <> I.LanguagesIDs THEN 1 ELSE 0 END
FROM INSERTED I JOIN DELETED D ON I.RegistrantID = D.RegistrantID 
WHERE D.CategoriesIDs <> I.CategoriesIDs 
    OR D.DesiredCategoriesIDs <> I.DesiredCategoriesIDs 
    OR D.LanguagesIDs <> I.LanguagesIDs

OPEN curRegs;
FETCH NEXT FROM curRegs INTO @RegistrantID, @CategoriesIDs, @DesiredCategoriesIDs, @LanguagesIDs, 
    @CategoryIDsChanged, @DesiredCategoriesIDsChanged, @LanguagesIDsChanged;

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @CategoriesIDs IS NOT NULL AND @CategoryIDsChanged = 1
    BEGIN
        -- delete existing rows at first
        DELETE dbo.hr_RegistrantCategories WHERE RegistrantID = @RegistrantID

        INSERT INTO dbo.hr_RegistrantCategories (RegistrantID, CategoryID)
        SELECT @RegistrantID, CAST(T.Data AS INT) 
        FROM dbo.hr_Split(@CategoriesIDs, '|') T
    END

    IF @DesiredCategoriesIDs IS NOT NULL AND @DesiredCategoriesIDsChanged = 1
    BEGIN
        -- delete existing rows at first
        DELETE dbo.hr_RegistrantDesiredCategories WHERE RegistrantID = @RegistrantID

        INSERT INTO dbo.hr_RegistrantDesiredCategories (RegistrantID, CategoryID)
        SELECT @RegistrantID, CAST(T.Data AS INT) 
        FROM dbo.hr_Split(@DesiredCategoriesIDs, '|') T
    END

    IF @LanguagesIDs IS NOT NULL AND @LanguagesIDsChanged = 1
    BEGIN
        -- delete existing rows at first
        DELETE dbo.hr_RegistrantLanguages WHERE RegistrantID = @RegistrantID

        INSERT INTO dbo.hr_RegistrantLanguages (RegistrantID, Language)
        SELECT @RegistrantID, CAST(T.Data AS INT) 
        FROM dbo.hr_Split(@LanguagesIDs, '|') T
    END

    FETCH NEXT FROM curRegs INTO @RegistrantID, @CategoriesIDs, @DesiredCategoriesIDs, @LanguagesIDs, 
        @CategoryIDsChanged, @DesiredCategoriesIDsChanged, @LanguagesIDsChanged;
END

CLOSE curRegs;
DEALLOCATE curRegs;

请建议如何解决它?

4

2 回答 2

2

每个事务只触发一次触发器,在单个事务中执行批量更新、删除或插入。

您可能需要使用光标或一段时间来保证为每一行触发触发器。

有没有办法在不使用游标的情况下循环遍历 TSQL 中的表变量?

于 2013-12-11T20:00:03.710 回答
2

尝试使用更新后:

CREATE TRIGGER [dbo].[trg_test]

ON [dbo].[test]
AFTER UPDATE 

AS BEGIN


END

或检查触发器是否处于活动状态:

SELECT t.name, t.is_disabled 
FROM sys.triggers t
WHERE t.name = 'trUpdateRegistrant'
于 2013-05-10T10:48:00.797 回答