I have a stored proc that has the following (simplified example):
DECLARE @id int = NULL
SELECT * FROM table1 t1
INNER JOIN table2 t2 ON ((@id IS NOT NULL) AND (t2.id = @id))
The purpose of this is to return all rows if @id is not provided, else return just rows matching @id.
Works as expected as long as @id is provided. But it returns no rows is @id is null.
I thought, maybe
INNER JOIN table t2 ON (@id IS NULL OR ((@id IS NOT NULL) AND (t2.id = @id)))
might work, but if @id is null, then it seems to return unending rows (I waited 30 seconds, and it was past 1M rows. (There are only 150 rows in table1)
I've read around, and most other examples to accomplish this seem to use dynamic SQL (which I'd rather not do), or the possibility of creating a temp table, which seems a little extreme for this kind of thing.
What are my options? Thank you.


I am doubtful on your table joining, tried to simplified your SQL query