where子句中的case语句

时间:2009-09-08 07:44:56

标签: sql-server

我有一个包含以下代码的存储过程。

 alter PROCEDURE [dbo].[usp_Product_GetProductByCategoryID] 


@CategoryID uniqueidentifier,
@IsCategory bit=0  
AS  
  BEGIN  

   SELECT     ProductId, ProductCode, ProductName, MRP, MaxDiscount, 
              ShortDescription, ThumbNailImagePath,ThumbNailImagePath1, 
              FullImagePath, IsActive, NoOfBuyer,   
              LongDescription, BrandID, SubCategoryID, CreatedDate,
              LargeThumbnailImagePath, VideoPath  

   FROM         TBM_Product  

   WHERE (case @IsCategory 
           when 0 then  TBM_Product.SubCategoryID
           when 1 then  TBM_Product.CategoryID 
       end) 
            = @CategoryID 

   *AND (case 
       when @IsCategory= 0 then TBM_Product.SubCategoryID = TBM_Product.SubCategoryID
       when @IsCategory= 1 then TBM_Product.SubCategoryID is null 
      end)* 

END  

我想要的是

if(@ IsCategory = 1)然后

   TBM_Product.SubCategoryID is null

否则

 void this and condition

如何实现这一点。在编译上述存储过程时,我收到“语法不正确=”错误。

3 个答案:

答案 0 :(得分:3)

不需要在where子句中使用case语句。而是使用AND / OR运算符。

ALTER PROCEDURE [dbo].[usp_Product_GetProductByCategoryID] 
    @CategoryID uniqueidentifier ,
    @IsCategory bit = 0  
AS  
BEGIN  

SELECT  [ProductId], 
        [ProductCode], 
        [ProductName], 
        [MRP], 
        [MaxDiscount],    
        [ShortDescription],   
        [ThumbNailImagePath],
        [ThumbNailImagePath1], 
        [FullImagePath], 
        [IsActive], 
        [NoOfBuyer],   
        [LongDescription], 
        [BrandID], 
        [SubCategoryID], 
        [CreatedDate],  
        [LargeThumbnailImagePath], 
        [VideoPath],
        @CategoryID = CASE @IsCategory 
                        WHEN 0 THEN  TBM_Product.SubCategoryID
                        WHEN 1 THEN  TBM_Product.CategoryID 
                      END   
FROM    [dbo].[TBM_Product]
WHERE   (@IsCategory = 0 AND TBM_Product.SubCategoryID = TBM_Product.SubCategoryID)
        OR (@IsCategory= 1 AND TBM_Product.SubCategoryID IS NULL)
END

答案 1 :(得分:1)

SELECT ... CASE在WHERE条件下不起作用,并且它们不像您编写的那样工作。你必须修改你的查询并写下这样的条件 -

...
WHERE
    (@IsCategory= 0 AND TBM_Product.SubCategoryID = TBM_Product.SubCategoryID)
    OR
    (@IsCategory= 1 AND TBM_Product.SubCategoryID IS NULL)

答案 2 :(得分:0)

and ((@Iscategory=1 and TBM_Product.SubCategoryID is null)
    or
    (@Iscategory = 0))