4

Basically I have to build a list of items from a SQL database however the user can choose to filter on any combination of 7 filters and can also choose a column to order by and also the order by direction.

As you can imagine this ends in a large number of different combinations to code for and the dataset is quite large so I'd like to avoid doing this in the application.

In my stored procedure so far I have tried:

  • Building a query string, although this is quite simple and easy to follow, it leaves the application open to SQL injection so I would rather avoid this.

  • Using a set of IF ELSE statements to run proper parameterised SQL however this quickly becomes a huge tree and will be a nightmare to maintain.

I'm not the first person that has needed a solution like this and there must be a better way than the above? Also as a side question is there a good way to do order by and order by direction in a parameterised way, besides doing lots of IFs?

1

2 Answers 2

2

For filtering, use the COELSCE to filter by any combination of conditions. In your stored procedure there would be a list of all parameters that the user would search for, then in the your query will be something like:

 SELECT * 
 FROM YourTable t
 WHERE 1 = 1
 AND t.FirstColumn = COALESCE(@FirstColumnParam, t.FirstColumn)
 AND t.SecodndColumn = COALESCE(@SecondColumnParam, t.SecondColumn) 
 ....

If any of the parameters is null, then the condition is skipped. and for 1=1 that's in case there is no filter coditions is passed to your query.

For Ordering: you can use the CASE statement to order by any choosen column:

ORDER BY ( CASE WHEN @OrderByParam = 1 Then FirstColumn ELSE .... END)
4
  • Will the optimizer see this is a SARG and use indexes if you use the COALESCE function?
    – buckley
    Jun 13, 2012 at 11:44
  • @buckley, No, I think it will create indexes in case It is written the way you wrote AND (FirstColumn = @FirstColumnParam OR @FirstColumnParam Is NULL) Jun 13, 2012 at 11:50
  • @MahmoudGamal thanks very much, works a treat! There are so many nice SQL keywords that I find out about every now and then like this!
    – radm4
    Jun 13, 2012 at 13:25
  • The COALESCE pattern will fail for nullable columns, because NULL does not equal NULL. Also, in some situations ISNULL performs much better than COALESCE, even though they appear equivalent. Jul 20, 2012 at 18:40
2

Building a query string, although this is quite simple and easy to follow, it leaves the application open to SQL injection so I would rather avoid this.

Not if you use sp_executesql and pass your parameters as arguments tot that sproc. Since you give your data as parameters there will be no sql injection

http://sqlinthewild.co.za/index.php/2009/04/03/dynamic-sql-and-sql-injection/

http://blogs.msdn.com/b/raulga/archive/2007/01/04/dynamic-sql-sql-injection.aspx

I've also tried using a set of IF ELSE statements to run proper parameterised SQL however this quickly becomes a huge tree and will be a nightmare to maintain.

Agree if you use IF ELSE but there is also a pattern called catch all queries

WHERE (ProductID = @Product Or @Product IS NULL)
AND (ReferenceOrderID = @OrderID OR @OrderID Is NULL)
...

More info here http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

Be sure to specify OPTION (RECOMPILE) at the end since otherwise your queries can suffer for what is called as parameter sniffing

Also as a side question is there a good way to do order by and order by direction in a parameterised way, besides doing lots of IFs?

Possible duplicate of Dynamic Sorting within SQL Stored Procedures

In the end you can with sp_executesql or catch all queries (this is a common problem with these 2 tried solutions). I usualy prefere catch all queries but don't forget to specify option (recompile).

2
  • You cannot pass a where clause as argument to sp_executesql. And if you build the SQL argument to sp_executesql dynamically, that is of course open for SQL injection.,
    – Andomar
    Jun 13, 2012 at 11:52
  • @Andomar I clarified the answer that you have to pass them as arguments to the sproc. I would just go for a catch all + option recompile, that would also simplify the dynamic ordering
    – buckley
    Jun 13, 2012 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.