我有以下触发器:
ALTER TRIGGER .[dbo].[trgAfterInsertComment]
ON .[dbo].[Comment]
AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @Id int;
declare @LoanId int;
declare @CopyId int;
declare @CustomerId int;
declare @Comment nvarchar(255);
--DECLARE cur CURSOR FOR
select @Id = Id from inserted
select @LoanId = LoanId from inserted
--select @CopyId = CopyId from deleted
--select @CustomerId = CustomerId from deleted
select @Comment = Comment from inserted
-- OPEN cur
--FETCH NEXT FROM cur INTO @Id, @ISBN, @Purchase_Date
--WHILE @@FETCH_STATUS = 0 BEGIN
-- your business logic
Declare @Title nvarchar(255);
select @Title = (Select Title from Book where ISBN = (select ISBN from copy where Id = (select CopyId from Loan where Id = @LoanId)))
select @CustomerId = (Select CustomerId from Loan where Id = @LoanId)
select @CopyId = (Select CopyId from Loan where Id = @LoanId)
insert into Activity("Heading", "Date")
values(Concat('New Comment added - Id: ', @Id, ' Title: ', @Title, ' Copy Id: ', @CopyId, ' Customer Id: ', @CustomerId, ' Comment: ', @Comment), GETDATE())
--FETCH NEXT FROM cur INTO @Id, @ISBN, @Purchase_Date
--END
--CLOSE cur
--DEALLOCATE cur
end
正如您所看到的,我已经注释掉了我用来处理多个插入的游标。有人可以告诉我如何在没有光标的情况下处理多个插入,因为阅读后我发现使用光标是一个坏主意吗?
使用上面的触发器,如果我尝试插入多行,如下所示:
USE [Library]
GO
INSERT INTO [dbo].[Comment]
([LoanId]
,[Comment])
VALUES
(47, 'test'),
(48, 'test'),
(50, 'test')
GO
只有第一行插入到我的Activity表中。谢谢你的帮助
答案 0 :(得分:3)
您需要将其设置为基于设置,使用变量和循环将导致问题。无法测试以下内容,但有类似的内容:
INSERT INTO Activity
(
Heading ,
[Date]
)
SELECT CONCAT('New Comment added - Id: ', I.id, ' Title: ', COALESCE(B.Title,''), ' Copy Id: ', COALESCE(L.CopyID,''), ' Customer Id: ', COALESCE(L.CustomerID,'')) ,
GETDATE()
FROM inserted AS I
LEFT JOIN Loan AS L ON I.loanId = L.loanId
LEFT JOIN Copy AS C ON C.Id = L.CopyId
LEFT JOIN Book AS B ON B.ISBN = C.ISBN;
答案 1 :(得分:2)
直接查询插入表。
insert into [dbo].[Comment] (LoanId, Comment)
select LoanId, Comment from inserted
您可以将选择查询更改为更复杂,以便仅使用查询来实现结果。