ELSE附近的语法不正确

时间:2014-04-17 01:25:02

标签: sql stored-procedures

我正在尝试创建一个存储过程,用于打印客户列表和他们购买的品牌。该程序生成的报告必须使用以下格式:

Customer Last Name1

BrandName1

BrandName2                ...

客户姓氏2

品牌

客户姓氏3

品牌

客户和品牌表由发票,行和产品表分隔。我已经使用连接将它们链接在一起,但是在使用IF和ELSE时我的代码中出现语法错误,而我无法弄清楚为什么会出错。

       CREATE PROCEDURE CustomerList

   (@Cust_LName VARCHAR(20), @Brand_ID INT = NULL)
   AS
   BEGIN

    IF(@Cust_LName IS NULL)
    DECLARE Customer_Cursor CURSOR FOR
        SELECT  DISTINCT C.Cust_LName, B.Brand_Name
        FROM    LGCustomer C
        LEFT JOIN LGInvoice I ON C.Cust_Code = I.Cust_Code
        INNER JOIN LGLine L ON I.Inv_Num = L.Inv_Num
        INNER JOIN LGProduct P ON L.Prod_SKU = P.Prod_SKU
        INNER JOIN LGBrand B ON P.Brand_ID = B.Brand_ID
        ORDER BY C.Cust_LName ASC
        OPEN    Customer_Cursor
        FETCH NEXT FROM Customer_Cursor INTO @Cust_LName
        WHILE (@@FETCH_STATUS = 0)
    BEGIN
    DECLARE Brand_Cursor CURSOR FOR
        SELECT  Brand_ID
        FROM    LGProduct
        WHERE   Brand_ID = @Brand_ID
        OPEN    Brand_Cursor
        FETCH NEXT FROM Brand_Cursor INTO @Brand_ID
        WHILE (@@FETCH_STATUS = 0)
    BEGIN
        PRINT @Brand_ID
        FETCH NEXT FROM Brand_Cursor INTO @Brand_ID
    END
    CLOSE Brand_Cursor
    DEALLOCATE Brand_Cursor
    FETCH NEXT FROM Customer_Cursor INTO @Cust_LName
    END
    CLOSE Customer_Cursor
    DEALLOCATE Customer_Cursor

    SELECT  *
    FROM    LGCustomer

    ELSE
    BEGIN
    SELECT  *
    FROM    LGProduct
    WHERE   Brand_ID = @Brand_ID
    END
    END
    GO

我尝试在ELSE之前删除END,并自行删除IF和ELSE,但是如果我这样做,它就不会显示我希望它们显示的结果。我在SQL方面比较新,所以我真的不确定我哪里出错了。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试这样,按程序对齐你的代码,你应该能够弄明白。

IF(@Cust_LName IS NULL)
BEGIN

...
...

END
SELECT  * FROM    LGCustomer
END
ELSE
BEGIN
SELECT  * FROM    LGProduct WHERE   Brand_ID = @Brand_ID
END
END
GO