Question

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.

Was it helpful?

Solution

SELECT * 
  FROM Listing l
 WHERE IsDeleted = 1 
   AND ( @MustHasPicture <> 1 OR 
         (@MustHasPicture = 1 AND l.id IN (
              SELECT listingid
              FROM ListingPictures
            )
         )
       )

OTHER TIPS

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)

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top