Using Parameters for SQL Server Queries and Stored Procedures

Problem

One of the benefits of SQL is the ability to write a query and use parameters
to dynamically act upon the resultset. Depending on the situation, there can be
benefits to parameterizing queries, but it is not always clear when or how to do
this. In this tip we look at different ways to pass in values as
parameters to queries and the advantages and disadvantages.

Solution

Providing some protection against SQL Injection Attacks under some circumstances

Generally, when creating a condition in a query where you might use one of several values, it makes sense to parameterize. But, as will be discussed later in this tip, there are cases where the query cannot be fully parameterized.

Parameterizing a Query By Making It a Stored Procedure

If you want to find the sales data for Jack, you could start with a non-parameterized query that just pulls up that data:

Under
some circumstances, SQL Server can attempt to parameterize this behind the scenes to facilitate execution plan reuse, but its ability to do that can be limited. If you want to use this query repeatedly to get the data for different sales people, you could instead parameterize the query and turn it into a stored procedure like:

Doing it this way explicitly tells SQL Server what the parameters are, which makes query execution plan reuse more likely. It also ensures that the salesperson value is handled in a way that is normally safer and makes SQL Injection Attacks through this procedure more difficult.

This is substantially different from a stored procedure that builds the query through concatenation like:

This second version builds a non-parameterized query using dynamic sql. It is simple to exploit a procedure like this in a SQL Injection Attack. It also does not explicitly tell SQL Server where the parameters are.

Parameterizing in T-SQL with sp_executesql

Another direct way to parameterize a query in T-SQL is to use
sp_executesql and explicitly add your parameters. It looks like:

With sp_executesql the first parameter is the SQL code to be executed, the second lists the parameters that will be supplied and indicates whether they are output variables, and then the actual parameters are passed into the procedure. Both the SQL statement and the list of parameters must be presented in unicode (nvarchar, nchar, or a string prefixed by N like the parameter list in the example.)

Parameterizing in SQL from other languages

Languages that interact with SQL tend to make it simple to parameterize. To parameterize a
SqlCommand put the names of the parameters in the CommandText and then use
Parameters.Add to add parameters that match the name to the command before executing. It looks like:

When the query cannot be (fully) parameterized

Parameterization brings several benefits, including some protection against SQL injection attacks under some circumstances. But there are certain types of dynamic queries that cannot be fully parameterized. For instance, SQL Server will not accept a table name or a column name as a parameter. If you tried to do it with sp_executesql, like:

The server merely returns a result set of "SalesPerson". Trying to use a parameter for a tablename in a query causes the server to try to interpret the parameter as a table variable and gives an error like: "Msg 1087, Level 16, State 1, Line 3 Must declare the table variable "@tableName"."

So a procedure meant to run against an
arbitrary table would need to actually build the SQL command by constructing the string. Other parts of that query could still be parameterized of course. A simplified example could look like:

However, building the string that way can make SQL Injection attacks simpler, especially if the user is directly prompted to supply the table or column names. Depending on the expected use cases, it may be wise to perform some string validation before execution. Ensuring the application runs with the
minimal necessary access to SQL Server can help mitigate that risk to a degree.

Summary

In general, properly applied parameterization can assist in security for SQL Server and can have
performance implications. But, some queries cannot be fully parameterized such as when the column names, table names, or other clauses need to be added or modified dynamically. When non-parameterized dynamic SQL is used, the performance and security implications should be kept in mind.

Post a comment or let the author know this tip helped.

All comments are reviewed, so stay on subject or we may delete your comment. Note: your email address is not published. Required fields are marked with an asterisk (*).

*Name
*Email
Email me updates

Signup for our newsletter
I agree by submitting my data to receive communications, account updates and/or special offers about SQL Server from MSSQLTips and/or its Sponsors. I have read the privacy statement and understand I may unsubscribe at any time.

If you use SQLCMD mode in Management Studio, you can parameterize your scripts with :SETVAR. The parameter values are added by simple text replacement before the query is sent to the server, so they can be used anywhere. Table names, database names, server names, string literals, or pieces of any of those. The script can be multiple batches separated by GO, and the SQLCMD variables are applied to the whole thing.

Parameter sniffing is expected behavior and is normally desirable. To perhaps oversimplify, if a query is called that is not in the cache, SQL server must compile it. When it does so, it will look at or "sniff" the parameters used for that query and optimize its execution plan for those values.

The "Parameter Sniffing Problem" arises if there is a plan in the cache, but the plan was suboptimal this time because it was optimized for parameters that would return a different cardinality. For instance, a query that would only return a few values might be best with a very different execution plan than one that would return 90% of the values in the table.

Although this problem can arise for just about any query, it is most common in queries that involve the use of "LIKE" and wildcards like "%".

Although this can be a performance problem in some situations, this problem is often well outweighed by the benefits of execution plan reuse, elegance of code, and (in some situations) security benefits that come from proper parameterization. It is also worth noting that using dynamic SQL or not parameterizing your code will not always prevent the "parameter sniffing problem" because later versions of SQL Server will sometimes parameterize simple queries behindt he scenes in order to gain the benefits of query plan reuse. The excellent tip "SQL Server Simpled and Forced Parameterization" by Brady Upton mentions this.

Now, if parameter sniffing does cause performance problems in your particular case there are a number of ways to address it. One way is to include Query Hints such as "Optimize for" as Greg Robidoux talked about in his tip. Greg Larson also has an article detailing how this problem can come up, why it often does not come up, and options on how to deal with it when it does come up that might be useful.

I agree by submitting my data to receive communications, account updates and/or special offers about SQL Server from MSSQLTips and/or its Sponsors. I have read the privacy statement and understand I may unsubscribe at any time.