NilushiH
NilushiH

Reputation: 29

IF inside where clause - SQL

Can I have a if statement inside a where clause as in the follwing.

SELECT DISTINCT *
FROM product p
          INNER JOIN product_to_vendor pv
        ON pv.product_id = p.product_id
WHERE pv.vendor_id = @vendorId AND p.site_id = @siteId AND
            IF (@productStatus < 4)
        BEGIN 
            p.[rank] = @productStatus 
        END

thanks

Upvotes: 3

Views: 868

Answers (1)

cctan
cctan

Reputation: 2023

SELECT DISTINCT *
FROM product p
INNER JOIN product_to_vendor pv
        ON pv.product_id = p.product_id
WHERE     pv.vendor_id = @vendorId 
      AND p.site_id = @siteId 
      AND (@productStatus < 4 AND p.[rank] = @productStatus)

I not sure about your requirements, but here it is showing how if-else can be constructed from boolean logic. Just assume the if (condition) is just another statement for AND.

Upvotes: 1

Related Questions