sql server - SQL add filter only if a variable is not null -
hi have query follows:
select route_id [route_id] route_master(nolock) route_ou = 2 , route_query = @l_s_query , lang_id = 1
here, " , route_query = @l_s_query" condition in clause should added when @l_s_query non empty. donot want write if else condition @l_s_query. there way handle in clause directly.thanks.
you can translate requirement :
select route_id [route_id] route_master(nolock) route_ou = 2 , (@l_s_query null or route_query = @l_s_query) , lang_id = 1 option (recompile)
the option (recompile)
optional can give better execution plans @ expense of compilation time discussed in canonical article on topic dynamic search conditions in t‑sql
or coalesce()
avoid or
:
where route_ou = 2 , coalesce(@l_s_query,route_query) = route_query , lang_id = 1
note: @jarlh said, if route_query
nullable, may cause issues becuase of null comparison, may want use first query.
another option of 2 separate queries using union all
, 1 each condition -
select .. .. @l_s_query null union select .. .. @l_s_query = route_query
on terms of performance,only last 1 use index, believe first 1 fastest, may change depanding on indexes, sizes of tables etc..
Comments
Post a Comment