插入错误后触发SQl

时间:2017-11-10 11:08:01

标签: sql sql-server triggers insert

我在将新行插入SQL表后尝试更新/插入值。我正在使用触发器来完成此操作,但我收到一个错误,我明白这意味着什么,但我不知道如何解决它。我的印象是我可以根据我声明的@id从插入的表中获取插入的行,该部分似乎可以工作,但为什么我得到错误,我不允许在我的“输入NULL值” invoicenumber“field(我知道它是PK,但我不会在这个字段中输入任何东西(它已经填充了插入本身的正确数据)。

那么,任何人都可以向我解释我做错了吗?

我使用的表格:

table delivery_invoice

id - int
invoicenumber(PK) - varchar(50)
amount6 - money
amount21 - money
distributor - int
payed - char(3)
deliverycosts - money
deliverydate - datetime
deliverytime - datetime
VATamount6 - calculated field
VATamount21 - calculated field
VATamountdelivery - int

我使用的触发器

USE TestDelivery
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      James
-- Create date: 11-08-2017
-- Description: change VATamountdelivery field after a new row is inserted
-- =============================================
CREATE TRIGGER trgVATAmountDelivery
ON  dbo.delivery_invoice 
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 @amount money
Declare @invoice varchar(50)
Select @id = id from inserted
Select @amount = VATamount21 from inserted

IF @amount > 0
insert into dbo.delivery_invoice(VATamountdelivery)
    values(21)
    else
insert into dbo.delivery_invoice(VATamountdelivery)
    values(6) 

END
GO

最后但并非最不重要的是我得到的错误:

Error. Cannot insert the value NULL into column 'invoicenumber', table 
'TestDelivery delivery_invoice'; column does not allow nulls. INSERT fails. 
The statement has been terminated.

任何帮助都会得到满足! 学家

1 个答案:

答案 0 :(得分:2)

您不希望插入带有该值的新行。我想你只想改变价值。

但是,您的触发器还有其他问题。特别是,从不假设inserted只包含一行。这只是一个等待发生的错误。

CREATE TRIGGER trgVATAmountDelivery ON dbo.delivery_invoice 
AFTER INSERT    
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
    SET NOCOUNT ON;

    update di
        set VATamountdelivery = (case when i.VATamount21 > 0 then 21 else 6 end)
        from dbo.delivery_invoice di join
             inserted i
             on i.id = di.id

END;