2009-09-08 148 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))