need help optimizing this sql expression
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
精彩评论