kramaswamy (11/19/2012)
Yeah - I've used the Dynamic SQL approach before, and it does work pretty well, but I'm not a huge fan of it. Never knew about the RECOMPILE option though, I'll have to try that out.Still, doesn't really help with the question at hand. I mean, yes - I could use the dynamic SQL solution, and that would solve my problem. If there is no better, more elegant solution, then I suppose I'll just go with that.
As per article, Dynamic SQL, most likely, would give you the best performance, but if you insist, there is another way to write your query:
DECLARE @TableB_ID INT
SELECT DISTINCT
A.ID
FROM TableA A
LEFT JOIN LinkTable LT ON LT.TableA_ID = A.ID
WHERE @TableB_ID IS NULL
OR LT.TableB_ID = @TableB_ID