我有以下触发器,当主表中的条目更新时,它应该在联结表中插入记录。但是这个触发器没有触发(它是先前发射的)
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;
请建议如何解决?
答案 0 :(得分:2)
尝试使用AFTER UPDATE:
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'
答案 1 :(得分:0)
每个事务只触发一次触发器,在单个事务中执行批量更新,删除或插入。
您可能需要使用光标或一段时间来保证每行都触发触发器。
Is there a way to loop through a table variable in TSQL without using a cursor?