开发者

need help optimizing this sql expression

开发者 https://www.devze.com 2023-01-14 12:49 出处:网络
in my query\'s WHERE clause i have this code: ..开发者_C百科. where @PageID in (...subquery...) or not exists(...subquery...)

in my query's WHERE clause i have this code:


..开发者_C百科.
where @PageID in (...subquery...) or not exists(...subquery...)
...

where the subquery is the same in both cases. that is, i want @PageID to appear in the subquery only if the subquery is not empty. is there a way to use the subquery once with the same effect?

thanks konstantin


Assuming your current query is like this

DECLARE @PageID INT = -100

SELECT *
FROM sys.objects
WHERE @PageID IN (SELECT number FROM  master.dbo.spt_values) 
   OR NOT EXISTS(SELECT number FROM  master.dbo.spt_values)

I think this is equivalent

SELECT *
FROM sys.objects
WHERE 
ISNULL((SELECT MIN(CASE WHEN number = @PageID THEN 0 ELSE 1 END) 
                                                       FROM dbo.spt_values),0)=0
0

精彩评论

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

关注公众号