This is somewhat of a sequel to Slow Exists Check. Alex's suggestion works and successfully avoids code repetition, but I still end up with a second issue. Consider the example below (From AlexKuznetsov). In it, I have two branches to handle 1 contraint. If I had 2 optional constraints, I would end up with 4 branches. Basically, the number of branches increases exponentially with the number of constraints.
On the other hand, if I use a Multi-Statement Table-valued function or otherwise use temporary tables, the SQL query optimizer is not able to assist me, so things become slow. I am somewhat distrustful of dynamic SQL (and I've heard it is slow, too).
Can anyone offer suggestions on how to add more constraints without adding lots of if statements?
Note: I have previously tried just chaining x is null or inpo = @inpo
together, but this is very slow. Keep in mind that while the inpo = @inpo
test can be handled via some sort of indexing black magic, the nullity test ends up being evaluated for every row in the table.
IF @inpo IS NULL BEGIN
SELECT a,b,c
FROM dbo.ReuseMyQuery(@i1)
ORDER BY c;
END ELSE BEGIN
SELECT a,b,c
FROM dbo.ReuseMyQuery(@i1)
WHERE inpo = @inpo
ORDER BY c;
END
Variation Two: 2 constraints:
IF @inpo IS NULL BEGIN
IF @inpo2 IS NULL BEGIN
SELECT a,b,c
FROM dbo.ReuseMyQuery(@i1)
ORDER BY c;
END ELSE BEGIN
SELECT a,b,c
FROM dbo.ReuseMyQuery(@i1)
WHERE inpo2 = @inpo2
ORDER BY c;
END
END ELSE BEGIN
IF @inpo2 IS NULL BEGIN
SELECT a,b,c
FROM dbo.ReuseMyQuery(@i1)
WHERE inpo = @inpo
ORDER BY c;
END ELSE BEGIN
SELECT a,b,c
FROM dbo.ReuseMyQuery(@i1)
WHERE inpo = @inpo AND
inpo2 = @inpo2
ORDER BY c;
END
END