I’m using SQL Server 2008.
I have an interesting scenario where a stored procedure (written by a “power user”) has an okay runtime of (around 4 seconds) if there’s data in the primary table. If the search value doesn’t exist, the run time averages out at about 3 minutes. Because of how the process works, and the web application that uses the procedure, it requires an empty result set in the case of no data.
I’ve tested the logic below with values that have data and values that don’t and the flow seems to work; however, when I put my actual query in the else statement, it seems like that part is always being evaluated despite my knowing that logic branch shouldn’t execute.
DECLARE @spId int
SELECT @spId = td.mainId
FROM dbo.PRIMARYTABLE
WHERE td.longId = @searchVal
IF @spId < 1 OR @spId IS NULL
BEGIN
select 'RETURN EMPTY RESULT SET' as test
END
ELSE
BEGIN
SELECT 'DO ACTUAL QUERY' as test
END
When I test this with a dummy value, such as 1111, the select ‘RETURN EMPTY RESULT SET’ as test is returned. When I use a value that I know exists, the SELECT ‘DO ACTUAL QUERY’ as test is returned. When I replace “SELECT ‘DO ACTUAL QUERY’ as test” with the actual heavy duty query and use the same non-existent dummy value, it still looks like the ELSE clause is reached.
What am I missing here?
Perhaps you are not showing everything. There is an counter-intuitive thing about assignment in select where no rows are returned – the value of variable will not be cleared. Paste this in SSMS:
@spid will be 2134. This is why you should always test using @@rowcount, in you case
There is also a possibility of duplicated data by longId, returning random mainid from rows that satisfy @searchval condition.
Other than that, I would not know.