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 ELSEstatements 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?
For filtering, use the
COELSCEto 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:If any of the parameters is null, then the condition is skipped. and for
1=1that’s in case there is no filter coditions is passed to your query.For Ordering: you can use the
CASEstatement to order by any choosen column: