无法创建存储过程

时间:2013-04-07 19:34:46

标签: sql sql-server

我遇到的问题是创建一个名为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附近给出错误的语法。我在网上发现了类似的帖子,但我总是遇到同样的错误。

2 个答案:

答案 0 :(得分: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
    

答案 1 :(得分: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