感谢您的回复,由于在评论文本中引用,我想要一些带有编号的评论。我不想用名字做出反应,有时一个人反应更多次,所以有了这个系统,我会知道这个人在回复哪一个。
所以今天我做了这个 INSTEAD OF INSERT 触发器:
CREATE TRIGGER InsertComments ON Comments
INSTEAD OF INSERT
AS
DECLARE @Inserted TABLE
(
ArticleId INT NOT NULL,
UserId INT NOT NULL,
CommentDate DATETIME NOT NULL,
Content NVARCHAR(1000) NOT NULL,
RowNumber INT NOT NULL
)
INSERT INTO @Inserted
SELECT ArticleId, UserId, CommentDate, Content, ROW_NUMBER() OVER (ORDER BY CommentDate) AS RowNumber
FROM INSERTED
DECLARE @NumberOfRows INT = (SELECT COUNT(*) FROM @Inserted)
DECLARE @i INT = 1
WHILE (@i <= @NumberOfRows)
BEGIN
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRAN
DECLARE @CommentId INT = (SELECT ISNULL(MAX(CommentId), 0)
FROM Comments WHERE ArticleId = (SELECT ArticleId
FROM @Inserted WHERE RowNumber = @i)) + 1
INSERT INTO Comments(CommentId, ArticleId, UserId, CommentDate, Content)
SELECT @CommentId, ArticleId, UserId, CommentDate, Content
FROM @Inserted WHERE RowNumber = @i
COMMIT
SET @i = @i + 1
END
我知道这不是完美的解决方案,但它完全符合我的需要。如果你们中的任何人有一些意见,我会很乐意阅读。