I have an ASP.NET MVC 3 app that lets users to create their own filters. Something like amount > 5 and amount <= 7, and so on. The user can choose both the amount value and the operator.
My problem is how to pass those filters to the stored procedure that retrieves the data. The stored procedure is already pretty complicated, meaning there are a lot of parameters passed which are checked to be null, so I can’t really apply the answer I found here: T-SQL Stored Procedure – Dynamic AND/OR Operator
Is there any other way I can do this?
Operators cannot be parameterized. Since you mention this is a stored procedure, the only option is to write the T-SQL inside the SP, and use sp_executesql, i.e.
This builds the query (
@sql) on the fly, but keeps the value (@value) parameterized throughout, so we only need to white-list the operator (@operator).Just to show how the value remains parameterized, we could also have used:
Here,
@pis the name of the parameter in the inner sql, and@valueis the name of the parameter in the stored procedure; the third/fourth/fifth/etc parameters tosp_executesqlare mapped to the parameters declared in the second parameter tosp_executesql(which in this example, declared just@p).Note that if this wasn’t a stored procedure, you could perform the query-construction step in C#, again keeping the value as a parameter.