-2

enter image description hereI want to apply filter in SQL query but in any order. What i mean is that if i have three parameters name para1, para2 and para3 and i want to apply only para1 and para3 parameters but do not want to apply para2 parameter in query or I want to apply only para3 parameter but don't want to apply para1 and para2 parameters in query.

In attached image if i want to apply filer on assigned_user_id and do not want to apply filer on Status or Dept column than result should show record filter on first parameter only.

Please help.

2 Answers2

2

I think what you want is to have a stored proc where you pass 3 params p1,p2,p3, and one or more of them might be null. I will leave how to pass null for an unused parameter from whatever your caller application is up to you.

The way to do the sql selection, is this.

where
   (@p1 is null null or column1=@p1)
   and (@p2 is null or column2=@p2)
   and (@p3 is null or column3=@p3)
TomC
  • 2,759
  • 1
  • 7
  • 16
0

Let ruby language for example. If you have any expressions to filter, you can manipulate with its as a strings:

conditions = {
  para2: '> 0',
  para3: '= 0',
  para4: '!= 100500',
}

so, you can collect them to where clause:

where_clause_rules = conditions.map do |key, value|
  "#{key} #{conditions[key]}"
end

where_clause = "WHERE #{where_clause_rules.join(' AND ')}"

and you have a result:

WHERE para2 > 0 AND para3 = 0 AND para4 != 100500

add this string to your sql:

SELECT * 
FROM your_table
#{where_clause}

you give result:

SELECT * 
FROM your_table
WHERE para2 > 0 AND para3 = 0 AND para4 != 100500

run sql:

Activerecord::Base.connection.execute(sql)

enjoy

Sergio Belevskij
  • 2,478
  • 25
  • 24