views:

564

answers:

3

I have a Where Clause that checks the existence of rows in a subquery, but I only want to execute that check if a bit is set to 1. So for example:

Select * from Listing l
Where
l.IsDeleted=1 
AND CASE WHEN @MustHasPicture = 1  THEN 
(
    EXISTS
    (
     SELECT NULL AS [EMPTY]
     FROM [dbo].[ListingPictures] AS [lp]
     INNER JOIN Listing l ON lp.ListingID=l.ID
    )
)
ELSE 1 END = 1

This syntax is wrong, and I'm hoping someone can point me in the right direction. Thanks.

+1  A: 

No need to do a case - if the first part of an and fails, the second part will not be performed.

select
  *
from
  Listing l
Where
 l.IsDeleted = 1
 and ((@MustHasPicture = 1 and exists (...)) or 1)
Abtin Forouzandeh
This results in a syntax error "An expression of non-boolean type specified in a context where a condition is expected, near ')'."Taking out the "OR 1" at the end makes it compile, but then it no returns NO listings in the event that the user passes in @MustHavePicture=0
Scott
+3  A: 
SELECT * 
  FROM Listing l
 WHERE IsDeleted = 1 
   AND ( @MustHasPicture <> 1 OR 
         (@MustHasPicture = 1 AND l.id IN (
              SELECT listingid
              FROM ListingPictures
            )
         )
       )
iammichael
This results in the same listings being returned in both cases.So, When @MustHavePicture=1, NON-pictured listings get returned. It looked like the best candidate to me though...:(
Scott
that's what I get for not really testing things. Edited to use another approach that I also haven't tested :-P
iammichael
Ooops, my bad. The Exists subquery needs to use a Where clause instead of an inner join. Listing l ends up being ANOTHER alias, rather than using the alias from one level above. So the subquery always returns true which is what was throwing off the results.
Scott
A: 

What about this one:

SELECT * FROM Listing l 
WHERE l.IsDeleted = 1 
AND (@MustHasPicture = 1 
    AND EXISTS(SELECT * FROM [dbo].[ListingPictures] AS [lp]  
    WHERE lp.ListingID = l.ID) 
OR @MustHasPicture = 0)

But where does the Value @MustHasPicture come from?

Ice