2016-05-02 43 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

非常感谢你 –