MS SQL Server 2012;我遇到以下语法错误:“关键字'BEGIN'附近的语法不正确。”

时间:2018-07-17 21:56:54

标签: sql sql-server stored-procedures

我的SQL Server 2012存储过程出现语法错误:

  

关键字“ BEGIN”附近的语法不正确

这是我的存储过程的代码:

CREATE PROCEDURE dbo.sp_UpdateOnHandQtyByMrchRcvd 
     (@pn_location_id SMALLINT, 
      @pn_item_id NUMERIC)  
    BEGIN TRAN compute_inv_loc_bal; --Syntax Error near the KEYWORD 'BEGIN'
BEGIN 
    DECLARE @p_location_id  NUMERIC,
            @p_item_id NUMERIC,
            @p_qty NUMERIC,
            @p_on_hand_qty NUMERIC,
            @count INT,
            @p_trans_id NUMERIC,
            @p_trans_type_id INT,
            @p_trans_category_id INT,
            @p_trans_ref_id NUMERIC,
            @p_trans_type_code VARCHAR(35)

    -- reset item location qty
    UPDATE posit_db.dbo.item_location
    SET qty_on_hand = 0,
        updated_by = user_name(), 
        updated_date = getdate()
    WHERE location_id = @pn_location_id;

    -- Merchandise Received
    -- trans_type = MerRcvd, 10, trans_category = Purchase, 3
    DECLARE get_trans_data CURSOR FOR
        SELECT 
            it.location_id, it.trans_id, it.item_id, it.trans_type_id, 
            it.trans_category_id, it.trans_ref_id, it.qty,
            itt.trans_type_code
        FROM    
            posit_db..inventory_trans it, posit_db..inventory_trans_type itt
        WHERE 
            it.trans_type_id = itt.trans_type_id AND
            it.trans_category_id = itt.trans_category_id AND
            it.location_id = @pn_location_id AND
            it.trans_ref_id in (SELECT trans_id FROM posit_db..mrch_dist) AND
            it.item_id in (SELECT item_id FROM posit_db..mrch_dist) ;

    OPEN get_trans_data

    FETCH get_trans_data INTO @p_location_id, @p_trans_id, @p_item_id, @p_trans_type_id,
                              @p_trans_category_id, @p_trans_ref_id, @p_qty, @p_trans_type_code

    WHILE (@@fetch_status <> -1)    

2 个答案:

答案 0 :(得分:0)

应该反过来。您首先开始过程块,然后开始其中的事务块,反之亦然

create procedure dbo.sp_UpdateOnHandQtyByMrchRcvd (
BEGIN
BEGIN TRAN compute_inv_loc_bal;

答案 1 :(得分:0)

编辑

我已经修改了原始答案。

在尝试构建存储过程时遇到的错误特别是由于参数声明引起的。它们周围应该没有打开/关闭括号。尽管不是必需的,但您可能要考虑将存储过程的代码包装在BEGIN / END块中,尽管正如Dan Guzman指出的那样,它在语法上是可选的。另外,我会在变量声明后移动BEGIN TRAN语句,尽管同样,它不是必需的。

CREATE PROCEDURE dbo.sp_UpdateOnHandQtyByMrchRcvd
    @pn_location_id  smallint, 
    @pn_item_id      numeric
AS
BEGIN
    DECLARE @p_location_id        numeric,
            @p_item_id            numeric,
            @p_qty                numeric, 
            @p_on_hand_qty        numeric,
            @count                int,
            @p_trans_id           numeric,
            @p_trans_type_id      int,
            @p_trans_category_id  int,
            @p_trans_ref_id       numeric,
            @p_trans_type_code    varchar(35)

    BEGIN TRAN compute_inv_loc_bal;

    /* REMAINDER OF YOUR STORED PROCEDURE GOES HERE... */

END