sql触发器无法使用变量插入行

时间:2013-10-02 09:02:00

标签: sql-server tsql triggers

当我使用此代码时,它会插入行

create trigger [dbo].[InsertInvPayment] on dbo.LG_001_01_PAYTRANS
after update
as
begin
  SET NOCOUNT ON;
   declare @InvLogicalRef int;
   declare @InvNumber varchar(50);
   select @InvLogicalRef = inserted.FICHEREF from inserted
   select @InvNumber = dbo.LG_001_01_INVOICE.DOCODE from dbo.LG_001_01_INVOICE where      dbo.LG_001_01_INVOICE.LOGICALREF = @InvLogicalRef
   insert into dbo.CRMINVPAYMENT(INVNUMBER) values('Hello')
  end

如果我像这样改变它

create trigger [dbo].[InsertInvPayment] on dbo.LG_001_01_PAYTRANS
after update
as
begin
  SET NOCOUNT ON;
   declare @InvLogicalRef int;
   declare @InvNumber varchar(50);
   select @InvLogicalRef = inserted.FICHEREF from inserted
   select @InvNumber = dbo.LG_001_01_INVOICE.DOCODE from dbo.LG_001_01_INVOICE where      dbo.LG_001_01_INVOICE.LOGICALREF = @InvLogicalRef
   insert into dbo.CRMINVPAYMENT(INVNUMBER) values(@InvNumber)
  end

它不起作用。我在第二个

中找不到错误

2 个答案:

答案 0 :(得分:1)

似乎你错过了选择InvLogicalRef的来源。它应该是

select @InvLogicalRef = inserted.FICHEREF from inserted

同样使用此触发器,您假设只有一条记录会立即更新。这将无法进行批量更新。

答案 1 :(得分:0)

为@InvLogicalRef指定值的行不完整。 由于该变量不包含值,因此无法为@InvNumber分配其值,因此您尝试将NULL字符串插入到CRMINVPAYMENT中。

确保从插入的表格中选择@InvLogicalRef的值。