触发器执行期间出错:将数据类型nvarchar转换为bigint时出错

时间:2015-01-28 03:35:09

标签: sql sql-server

我创建了一个触发器,必须更新Account表中的总金额。每当从Sale表更新某些数据时,触发器会执行计算当前数量的存储过程并将其插入Account中,但是当它即将更新Account表时,会发生一些非常奇怪的错误:

  

第5行中的数据未提交错误来源:.Net SqlClient   DataProvider错误消息:将数据类型nvarchar转换为错误   BIGINT。声明已经终止。

下面是Sale的触发器脚本:

CREATE TRIGGER [dbo].[Trigger_Sale]
ON [dbo].[Sale]
FOR DELETE, INSERT, UPDATE
AS
BEGIN
    exec ComputeAccountAmount ID_Account
END

程序ComputeAccountAmount

CREATE PROCEDURE [dbo].[ComputeAccountAmount]
@IdAccount bigint
AS
begin transaction
    update Account set AccountAmount = (SELECT sum(AmountSold) 
        from Sale
        where @IdAccount = ID_Account)
    where @IdAccount = ID_Account
commit

我已经检查了程序使用的所有类型,但是它的表格和一切都是bigint,如下所示:

    CREATE TABLE [dbo].[Account] (
    [ID_Account]     BIGINT IDENTITY (1, 1) NOT NULL,
    [ExpireDate]     DATE   NOT NULL,
    [PurchaseLimit]  MONEY  NOT NULL,
    [OpeningDate]    DATE   NOT NULL,
    [ID_Customer]    INT    NOT NULL,
    [AccountAmount]  MONEY  NULL,
    CONSTRAINT [PK_Account] PRIMARY KEY CLUSTERED ([ID_Account] ASC),
    CONSTRAINT [FK_Account_Customer] FOREIGN KEY ([ID_Customer]) REFERENCES [dbo].[Customer] ([ID_Customer]) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE [dbo].[Sale] (
    [ID_Sale]    INT          IDENTITY (1, 1) NOT NULL,
    [SaleDate]   DATE NOT NULL,
    [AmountSold] MONEY        NOT NULL,
    [ID_Account] BIGINT       NULL,
    PRIMARY KEY CLUSTERED ([ID_Account] ASC)
);

为了测试,我使用Visual Studio手动验证触发器。发生了什么事?

1 个答案:

答案 0 :(得分:0)

显然你的触发器有语法错误

CREATE TRIGGER [dbo].[Trigger_Sale]
ON [dbo].[Sale]
FOR DELETE, INSERT, UPDATE
AS
BEGIN
    exec ComputeAccountAmount ID_Account
END

什么是ID_Account?它会抛出错误

enter image description here

您需要从触发器中的INSERTEDDELETED表中选择不同的帐户ID,并为每个帐户exec ComputeAccountAmount选择一个帐户ID。类似的东西:

CREATE TRIGGER [dbo].[Trigger_Sale] ON [dbo].[Sale]
    FOR DELETE, INSERT, UPDATE
AS
    BEGIN
        DECLARE @AccountID BIGINT

        DECLARE trCur CURSOR FAST_FORWARD READ_ONLY
        FOR
            SELECT  AccountID FROM    DELETED
            UNION
            SELECT  AccountID FROM    INSERTED

        OPEN trCur

        FETCH NEXT FROM trCur INTO @AccountID

        WHILE @@FETCH_STATUS = 0
            BEGIN

                EXEC ComputeAccountAmount @AccountID

                FETCH NEXT FROM trCur INTO @AccountID

            END

        CLOSE trCur
        DEALLOCATE trCur
    END