2016-05-02 44 views
-1

我在嘗試執行此查詢時遇到錯誤。如何使用SQL服務器查詢修復此錯誤

這是錯誤 (MSG 156,級別15,狀態1,過程SP_GetAllProducts,行關鍵字 '爲' 43 附近有語法錯誤。)

並且這些是我的查詢碼

create procedure [dbo].[SP_GetAllProducts] (@CategoryID INT) 
as 
    begin 
     begin try 
      if(@CategoryID <> 0) 
       begin 
        select * 
        from (select P.CategoryID, 
           P.ProductID, 
           P.Name, 
           P.Price, 
           P.ImageUrl, 
           C.CategoryName, 
           P.ProductQuantity, 
           Isnull(Sum(CP.TotalProduct), 0)      as ProductSold, 
           (P.ProductQuantity - Isnull(Sum(CP.TotalProduct), 0)) as AvailableStock 
          from Products P 
           inner join Category C 
              on C.CategoryID = P.CategoryID 
           left join  CustomerProducts CP 
              on CP.ProductID = P.ProductID 
          group by P.ProductID, 
            P.Name, 
            P.Price, 
            P.ImageUrl, 
            C.CategoryName, 
            P.ProductQuantity, 
            P.CategoryID) StockTable 
          where AvailableStock > 0 
           and CategoryID = @CategoryID 
       end 
      else 
       begin 
        select * 
        from (select P.CategoryID, 
           P.ProductID, 
           P.Name, 
           P.Price, 
           P.ImageUrl, 
           C.CategoryName, 
           P.ProductQuantity, 
           Isnull(Sum(CP.TotalProduct), 0)      as ProductSold, 
           (P.ProductQuantity - Isnull(Sum(CP.TotalProduct), 0) as AvailableStock 
          from Products P 
           inner join Category C 
             on C.CategoryID = P.CategoryID 
           left join CustomerProducts CP 
             on CP.ProductID = P.ProductID 
          group by P.ProductID, 
            P.Name, 
            P.Price, 
            P.ImageUrl, 
            C.CategoryName, 
            P.ProductQuantity, 
            P.CategoryID) StockTable 
          where AvailableStock > 0 
       end 
      end try 

      begin catch 
       print('Error occurd') 
      end catch 
    end 
+0

哪個線43? (請刪除其餘的程序) –

回答

1

你錯過了一個右括號,看到IF塊中的同一行,它有三個右括號,而else部分只有兩個!

(P.ProductQuantity - ISNULL(薩姆(CP.TotalProduct),0))作爲AvailableStock

+0

非常感謝你 –