sql server - MS SQL - JOIN only if parameter exists in stored proc -


i have stored proc has following (simplified example):

declare @id int = null select * table1 t1 inner join table2 t2 on ((@id not null) , (t2.id = @id)) 

the purpose of return rows if @id not provided, else return rows matching @id.

works expected long @id provided. returns no rows @id null.

i thought, maybe

inner join table t2 on (@id null or ((@id not null) , (t2.id = @id))) 

might work, if @id null, seems return unending rows (i waited 30 seconds, , past 1m rows. (there 150 rows in table1)

i've read around, , other examples accomplish seem use dynamic sql (which i'd rather not do), or possibility of creating temp table, seems little extreme kind of thing.

what options? thank you.

i doubtful on table joining, tried simplified sql query

declare @id int = null select *  table1 t1 inner join table2 t2 on  t1.id=t2.id @id null or t2.id = @id 

Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -