2009-09-08 97 views
1

我有一个存储过程使用下面的代码。案例声明在哪里条款

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 

我要的是

如果(@ IsCategory = 1),则

TBM_Product.SubCategoryID is null 

其他

void this and condition 

如何实现this.I我越来越“近不正确的语法=“编译上述存储过程时出现错误。

+0

从你的代码看起来好像你试图在WHERE子句中设置@CategoryID变量? – Kane 2009-09-08 07:53:27

回答

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 
+0

不错的一个。我喜欢。 – 2009-09-08 08:06:52

+0

这部分:“AND TBM_Product.SubCategoryID = TBM_Product.SubCategoryID”并不是真的必要,因为它们是相同的字段,除非我遗漏了一些东西。 – patmortech 2009-09-08 08:09:46

+0

AND TBM_Product.SubCategoryID = TBM_Product.SubCategoryID被添加到无效的where子句,即其中(1 = 1) – Rohit 2009-09-08 08:14:43

1

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

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

尝试

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