0

我已经编写了这个存储过程并且它执行但它不会更新客户。问题是:创建一个名为 prc_cus_balance_update 的过程,它将发票编号作为参数并更新客户余额。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE PRC_CUS_BALANCE_UPDATE3 

    @INV_NUMBER INT 

AS

BEGIN

    DECLARE @CUS_CODE INT

    SELECT @CUS_CODE=CUS_CODE
    FROM INVOICE
    WHERE @INV_NUMBER=INV_NUMBER

    UPDATE CUSTOMER
    SET CUS_BALANCE=CUS_BALANCE + 
        (SELECT INV_TOTAL FROM INVOICE WHERE @INV_NUMBER=INV_NUMBER)
    WHERE @CUS_CODE=CUS_CODE

END
GO
4

2 回答 2

0

Try putting some better bulletproofing in. Multiple rows, null values, and the like, can all cause problems with how you currently have it. Here's a stab at it, without me knowing the specifics of your data model (it may not be appropriate to sum together the totals from invoices, I'm just saying you could have multiple rows and need to deal with that).

CREATE PROCEDURE PRC_CUS_BALANCE_UPDATE3 
    @INV_NUMBER INT 
AS
BEGIN

    DECLARE @CUS_CODE INT

    SELECT 
        TOP 1 @CUS_CODE = CUS_CODE
    FROM 
        INVOICE
    WHERE 
        INV_NUMBER=@INV_NUMBER

    IF @CUS_CODE IS NOT NULL
    BEGIN
        UPDATE 
            CUSTOMER
        SET 
            CUS_BALANCE = ISNULL(CUS_BALANCE, 0.0) + 
            ISNULL(
                (SELECT 
                    SUM(INV_TOTAL) 
                FROM 
                    INVOICE 
                WHERE 
                    @INV_NUMBER = INV_NUMBER), 
            0.0)
        WHERE 
            CUS_CODE = @CUS_CODE    
    END
END
GO
于 2013-04-08T18:20:51.277 回答
0

在开发过程中,我会添加一些“额外内容”来弄清楚发生了什么。

伪代码如下。

您要确保找到匹配的行。并且您要确保至少有一行被实际更新。

我并不是说下面的代码是“生产就绪”。但会显示概念。

CREATE PROCEDURE PRC_CUS_BALANCE_UPDATE3 

    @INV_NUMBER INT 

AS

BEGIN

    DECLARE @CUS_CODE INT
    DECLARE @MYROWCOUNT INT

    SELECT @CUS_CODE=CUS_CODE
    FROM INVOICE
    WHERE @INV_NUMBER=INV_NUMBER

    if(Not(@CUS_CODE IS NULL))
        BEGIN

        SET NOCOUNT OFF

        UPDATE CUSTOMER
        SET CUS_BALANCE=CUS_BALANCE + 
            (SELECT INV_TOTAL FROM INVOICE WHERE @INV_NUMBER=INV_NUMBER)
        WHERE @CUS_CODE=CUS_CODE


        select @MYROWCOUNT = @@ROWCOUNT

        if(@MYROWCOUNT <=0)
            BEGIN
                print 'No row updated.    :<'
            END


        SET NOCOUNT OFF


        END
    ELSE
        BEGIN
            print "@CUS_CODE match not found."
        END

END
GO
于 2013-04-08T15:24:16.117 回答