我有这个过程,它将记录从一个表插入另一个表。目标表具有名为LeadId
的标识列
Create Procedure prcInsertPrd
As
Begin
Begin Transaction
Declare @Identity int
Insert into Temp_ProductsArchive (column1,column2,column3) select
(column1,column2,column3)
from Temp_Products
if(@@Error=0)
Begin
Commit
End
else
Begin
Rollback
End
End
然后我写了一个Insert Trigger,它将从插入的表中获取LeadId并将其插入另一个表中,其他值为 -
Alter TRIGGER trgInsertTopProducts
ON Temp_ProductsArchive
AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @LeadId as int
Select @LeadId=LeadId from inserted
print @LeadId
Insert into Temp_ProductsTop(column4,LeadID,Column5,column6) Select column4,@LeadID 'LeadID',column 5,column6 from Temp_Products
END
GO
问题是我得到的第一个生成的LeadiD并非所有LeadIds。 Temp_ProductsTop表中的LeadiD列仅对记录数重复此值
答案 0 :(得分:2)
您的触发器存在严重问题。编写触发器时,必须假定它可能被多行调用。即inserted
表可能包含多行,这意味着您必须加入到插入的表中。
我不确定你要在代码中实现什么,但是你需要重写这样的东西:
Alter TRIGGER trgInsertTopProducts
ON Temp_ProductsArchive
AFTER INSERT AS
BEGIN
SET NOCOUNT ON;
insert into Temp_ProductsTop
(ProductID,LeadID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued)
Select ProductID, inserted.LeadID, ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued
from
Temp_Products
inner join inserted on inserted.Leadid = ?
END
GO
在哪里?代表你加入的table.column。您想为每个LeadId添加temp_products吗?
答案 1 :(得分:-2)
“inserted
”是一个伪插入,包含插入的每个项目的行。触发器仅触发一次总计,而不是每次插入一次!
您可能需要使用游标循环插入的记录,一次处理一个。也许:
Alter TRIGGER trgInsertTopProducts
ON Temp_ProductsArchive
AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @LeadId as int
declare c CURSOR READ_ONLY for
select LeadId from inserted
open c
fetch next from c into @LeadId
while @@FETCH_STATUS = 0
BEGIN
Insert into Temp_ProductsTop(ProductID,LeadID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued) Select ProductID,@LeadID 'LeadID',ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued from Temp_Products
fetch next from c into @LeadId
END
close c
deallocate c
END
(请注意,我刚刚在此处输入此内容并且未进行语法检查或测试)