0

I'm trying to generate reports that has multiple search filters and I need those search filters to be able to take multiple values as search parameters.

Create Proc [procedure_name](
  @name nvarchar(50) null,
  @center nvarchar(3)null,
  @branch nvarchar(6)null
)
As
Begin
  Select [column1], [column2], [column3], [column4]
  from table1 a
  left join table2 b
  on a.cid=b.cid and a.acc=b.acc
  Where @name is null or a.Name=@name
    and @center is null or a.center=@center
    and @branch is null or a.branch=@branch
End

I need those search parameters to be able to take multiple values and filter them in the same table i.e. instead of @name = 'Mark' gives all result that has Mark I need @name = 'Mark', 'James', 'Adam' that give all results that has Mark, James and Adam.

Powkachu
  • 2,170
  • 2
  • 26
  • 36

2 Answers2

0

Use an SplitString function, like this one : T-SQL split string

Now your query can filter multiple values if you pass them separated by commas. @name = 'Mark,James,Adam'

Instead of :

@name is null or a.Name=@name

use :

@name is null or a.Name in (select Name from dbo.splitstring(@name))

PS: by the way, when using this kind of catch-all statements I always add option(recompile) at the end, so the SQL engine recalculates the execution plan depending on the parameters that you have passed.

Marc Guillot
  • 6,090
  • 1
  • 15
  • 42
0

First, your existing logic is wrong. It should be:

where (@name is null or a.Name = @name) and
      (@center is null or a.center = @center) and
      (@branch is null or a.branch = @branch)

For your fix:

where (@name is null or a.Name in (select value from string_split(@name)) and
      (@center is null or a.center in (select value from string_split(@center)) and
      (@branch is null or a.branch in (select value from string_split(@branch))
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786