1

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
  • 6,874
  • 22
  • 70
  • 139

3 Answers3

2

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
  • 38,630
  • 5
  • 53
  • 82
1

Try this Where clause

where t.id in (select item from dbo.ufnSplit(@ids,',')) or nullif(@ids,'') is null;
Pரதீப்
  • 88,697
  • 17
  • 124
  • 160
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
  • 21,369
  • 9
  • 63
  • 79