开发者

SQL Server Where Clause Case Statement?

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 开发者_Go百科END = 1

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


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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜