0

我遇到的问题是创建一个名为的过程prc_cus_balance_update,它将发票编号作为参数并更新客户余额(提示您可以使用声明部分定义一个 totinv 编号变量来保存计算出的发票总额)

到目前为止我有

ALTER PROCEDURE [dbo].[PRC_CUS_BALANCE_UPDATE]
   (@INVID INT)
AS
   DECLARE @INVTOT INT
   DECLARE @CUSID INT

   BEGIN
     SET NOCOUNT ON;

     SELECT CUS_CODE INTO CUSID
     FROM INVOICE
     WHERE INVOICE.INV_NUMBER = @INVID

     IF CUSID > 0 
        UPDATE CUSTOMER
        SET CUS_BALANCE = CUS_BALANCE +
                          (SELECT INV_TOTAL
                           FROM INVOICE
                           WHERE INV_NUMBER = INVID)
        WHERE CUS_CODE = CUSID
     END IF
   END

但是每次我尝试编译它时,它都会在关键字 END 附近给我一个不正确的语法。我在网上找到了类似的帖子,但我总是以同样的错误告终。

4

2 回答 2

4

在您的 SP 似乎是用其中编写的 Transact-SQL 中,其语法IF如下:

IF Boolean_expression 
     { sql_statement | statement_block } 
[ ELSE 
     { sql_statement | statement_block } ]

如您所见,没有关闭END IF。因此,一种解决方案是简单地删除END IF,在这种情况下,您的IF陈述将是

IF CUSID > 0 
    UPDATE CUSTOMER
    SET CUS_BALANCE = CUS_BALANCE +
        (SELECT INV_TOTAL
         FROM INVOICE
         WHERE INV_NUMBER = INVID)
    WHERE CUS_CODE = CUSID
;

如果您希望IF语句以 结尾END,请将正文包含在一个BEGIN…END块中:

IF CUSID > 0 
BEGIN
    UPDATE CUSTOMER
    SET CUS_BALANCE = CUS_BALANCE +
        (SELECT INV_TOTAL
         FROM INVOICE
         WHERE INV_NUMBER = INVID)
    WHERE CUS_CODE = CUSID;
END;

还有其他问题。似乎对变量的一些引用@CUSID并不@INVTOT@字符开头。此外,您似乎正在使用SELECT INTO为变量赋值。(你是从 MySQL 转换这个 SP 吗?)

要解决这些问题:

  1. 在 Transact-SQL 中,变量名称始终以@字符开头,无论是在声明中还是在引用中。

  2. 要将值分配给变量,请使用以下语法:

    SELECT @varname = ...
    [ FROM ...
    WHERE ... ]
    

    因此,在您的情况下, SELECT 语句可能应该是这样的:

    SELECT @CUSID = CUS_CODE
    FROM INVOICE
    WHERE INVOICE.INV_NUMBER = @INVID
    
于 2013-04-07T19:54:49.113 回答
1

也许还有其他一些问题:

CREATE PROCEDURE [dbo].[PRC_CUS_BALANCE_UPDATE]  --<<<<use CREATE to create !
   (@INVID INT)
AS
   DECLARE @INVTOT INT  --<<<<<<what is the point of this variable as it is not used?
   DECLARE @CUSID INT

   BEGIN
     SET NOCOUNT ON;

     /*<<<<if the following is only testing for the existence within INVOICE table then<<< 
     SELECT CUS_CODE 
     INTO CUSID
     FROM INVOICE
     WHERE INVOICE.INV_NUMBER = @INVID

     IF CUSID > 0 
     <<<<replace with following<<<<<*/
     IF EXISTS (SELECT 1 FROM INVOICE WHERE INVOICE.INV_NUMBER = @INVID)   

        BEGIN  --<<<<<as already mentioned
        UPDATE CUSTOMER
        SET CUS_BALANCE = CUS_BALANCE +
                          (SELECT INV_TOTAL
                           FROM INVOICE
                           WHERE INV_NUMBER = INVID) --<<<is this supposed to be =@INVID ?
        WHERE CUS_CODE = CUSID  --<<<this looks odd as it seems you are trying to say "CUS_CODE = <some table created earlier>" ?
        END;  --<<<<<as already mentioned
     END IF
   END
于 2013-04-07T20:58:50.543 回答