可能的问题在这里 -
CREATE TRIGGER dbo.Posts_Raw_To_Queue_Trigger
ON SendNotificationPostsRaw
-- for view
INSTEAD OF INSERT
-- OR
-- for table
AFTER INSERT
AS BEGIN
DECLARE
@PostID UNIQUEIDENTIFIER
, @UserID UNIQUEIDENTIFIER
, @ProfID INT
, @Email NVARCHAR(100)
, @CreationTime DATETIME
, @SpecialityID INT
SELECT @ProfID = ProfessionalID
, @Email = Email
FROM Professionals
WHERE UserID = @UserID
-- this posible return invalid result (random record from inserted sequence)
SELECT @PostID = I.PostID
, @UserID = I.UserID
, @CreationTime = I.CreationTime
FROM INSERTED I
DECLARE post_relation_cursor CURSOR LOCAL READ_ONLY FAST_FORWARD FOR
SELECT CategoryID
FROM dbo.PostCategoryRelations
WHERE PostId = @PostID;
OPEN post_relation_cursor;
FETCH NEXT FROM post_relation_cursor INTO @SpecialityID
WHILE @@FETCH_STATUS=0 BEGIN
INSERT INTO SendNotificationPostsQueue (
UserID
, PostID
, SpecialityID
, TemplateID
, CreationTime
, SendTime
, JSONParameters
)
SELECT
@UserID
, @PostID
, @SpecialityID --- !!!
, 1
, '04/11/2013'
, '04/11/2013'
, ''
FETCH NEXT FROM post_relation_cursor INTO @SpecialityID;
END;
CLOSE post_relation_cursor;
DEALLOCATE post_relation_cursor;
END
更新
如果我理解正确的话,业务逻辑一定是这样的:
CREATE TRIGGER dbo.Posts_Raw_To_Queue_Trigger
ON dbo.SendNotificationPostsRaw
[INSTEAD OF]/[AFTER] INSERT
AS BEGIN
SET NOCOUNT ON;
DECLARE
@PostID UNIQUEIDENTIFIER
, @UserID UNIQUEIDENTIFIER
, @ProfID INT
, @Email NVARCHAR(100)
, @CreationTime DATETIME
, @SpecialityID INT
DECLARE cur CURSOR LOCAL READ_ONLY FAST_FORWARD FOR
SELECT
i.PostID
, i.UserID
, ProfID = p.ProfessionalID
, p.Email
, i.CreationTime
, pcr.CategoryID
FROM INSERTED i
JOIN dbo.Professionals p ON i.UserID = p.UserID
JOIN dbo.PostCategoryRelations pcr ON i.PostID = pcr.PostID
OPEN cur
FETCH NEXT FROM cur INTO
@PostID
, @UserID
, @ProfID
, @Email
, @CreationTime
, @SpecialityID
WHILE @@FETCH_STATUS = 0 BEGIN
INSERT INTO dbo.SendNotificationPostsQueue
(
UserID
, PostID
, SpecialityID
, TemplateID
, CreationTime
, SendTime
, JSONParameters
)
SELECT
@UserID
, @PostID
, @SpecialityID
, 1
, @CreationTime
, @CreationTime
, ''
FETCH NEXT FROM cur INTO
@PostID
, @UserID
, @ProfID
, @Email
, @CreationTime
, @SpecialityID
END
CLOSE cur
DEALLOCATE cur
END