简体   繁体   中英

Rewriting dynamic SQL in to stored procedure

I see that this has been asked before in this post and have also looked at the WHEN-THEN construct but it really doesn't answer some of the questions.

Presently in the code a SQL query is built using a StringBuilder like this:

buildSearchQuery.Append("SELECT * FROM Policy WHERE Field_1 = '" + param_1 + "'");

if (Condition 2){
    buildSearchQuery.Append("AND Field_2 = '" + param_2 + "' ");
}
if (Condition 2)
{
   buildSearchQuery.Append("AND Field_3 = '" + param_3 + "' ");
}
...

You get the picture. There is a total of 20 of these parameter values and my task was to create a stored procedure and pass these values as parameters.

Do I create a stored procedure with all the parameters and do the logic there, if so I'm not sure how. Something like this?

SELECT * FROM TABLE WHERE Field_1 = @param_1
IF(@param_2 <> NULL)
    AND Field_2 = param_2
...

These parameters won't always have values so they cannot be part of the query. What is best way to make this work keeping in mind performance?

your stored procedure will have 3 parameters @param_1, @param_2, @param_3

Default value for these parameters can be set to NULL.

The condition inside the stored procedure will be like this

WHERE  ( @param_1 is NULL or field_1 = @param_1)
       AND 
       ( @param_2 is NULL or field_2 = @param_2)
       AND
       ( @param_3 is NULL or field_3 = @param_3)

OPTOIN(RECOMPILE)

Adding OPTION(RECOMPILE) rebuilds the execution plan every time that your query executes, with OR conditions this would be beneficial.

Since these are all nullable parameters, you could use coalesce in the where instead of the ORs inside the parens. I think it reads a bit better.

WHERE coalesce(@param_1, field_1)
AND
coalesce(@param_2, field_2)
AND
coalesce(@param_3, field_3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM