3

I have a query like this,

with t as (
      <your query here>
     )
select t.id, t.name, t.randomid, trand.name as randomname
from t left join
     t trand
     on t.randomid = trand.id
where t.id in (select item from dbo.ufnSplit(@ids,','));

Here is code for ufnSplit

How can I add check so that if @ids is null or empty only then use where condition, I want this condition only if @ids is not null or empty ?

where t.id in (select item from dbo.ufnSplit(@ids,','));
Community
  • 1
  • 1
Mathematics
  • 7,314
  • 25
  • 77
  • 152

3 Answers3

3

This will check if @ids is null or empty, and then check the where clause.

with t as (
      <your query here>
     )
select t.id, t.name, t.randomid, trand.name as randomname
from t left join
     t trand
     on t.randomid = trand.id
where @ids = '' 
   or @ids is null
   or t.id in (select item from dbo.ufnSplit(@ids,','))
sagi
  • 40,026
  • 6
  • 59
  • 84
1

Try this Where clause

where t.id in (select item from dbo.ufnSplit(@ids,',')) or nullif(@ids,'') is null;
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
1

You can just use a conditional WHERE clause like so:

with t as (
      <your query here>
     )
select t.id, t.name, t.randomid, trand.name as randomname
from t left join
     t trand
     on t.randomid = trand.id
where @ids IS NULL OR t.id IN (select item from dbo.ufnSplit(@ids,','));

So if it's NULL it will return everything, otherwise it will evaluate the OR part of the WHERE clause.

You may need to edit the function: dbo.ufnSplit to handle NULL input gracefully for this to work.

Tanner
  • 22,205
  • 9
  • 65
  • 83