SQL Server Cannot use IIF in where clause

snz8szmq  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(113)

I cannot use IIF in the Where clause, I'm trying to filter by brandId if @BRAND_IDS exists, I will use this for filtering the data, if not just select data that the BRAND_ID is not equal to 0.

.....
 WHERE  pit.Item_Enable = 1
      AND p.Product_Enable = 1
      AND pit.Item_SellPrice > 0
      AND pit.Item_ListPrice > 0
    AND Product_Catalog in (select CATALOG_LV3_ID from @CatalogSearch)
 AND IIF(@BRAND_IDS IS NOT NULL, BRAND_ID IN (select b.BRAND_ID from @Brands b), BRAND_ID <> 0)

zzzyeukh

zzzyeukh1#

IIF() needs to return a value, not an expression and so you cannot use it in the way you're trying to.

But all is not lost! I think this is equivalent to what you're trying to do with the IIF() :

(
    (@BRAND_IDS IS NOT NULL AND BRAND_ID in (select b.BRAND_ID from @Brands b))
    OR (@BRAND_IDS IS NULL AND BRAND_ID <> 0)
)

相关问题