The Curse and Blessings of Dynamic SQL

An SQL text by Erland Sommarskog, SQL Server MVP. Latest revision: 2011-06-23. An earlier version of this article is also available in German. Translations provided by SQL Server MVP Frank Kalis.

Introduction
If you follow the various newsgroups on Microsoft SQL Server, you often see people asking why they can't do:
SELECT * FROM @tablename SELECT @colname FROM tbl SELECT * FROM tbl WHERE x IN (@list)

For all three examples you can expect someone to answer Use dynamic SQL and give a quick example on how to do it. Unfortunately, for all three examples above, dynamic SQL is a poor solution. On the other hand, there are situations where dynamic SQL is the best or only way to go. In this article I will discuss the use of dynamic SQL in stored procedures and to a minor extent from client languages. To set the scene, I start with a very quick overview on application architecture for data access. I then proceed to describe the feature dynamic SQL as such, with a quick introduction followed by the gory syntax details. Next, I continue with a discussion on SQL injection, a security issue that it is essential to have good understanding of when you work with dynamic SQL. This is followed by a section where I discuss why we use stored procedures, and how that is affected by the use of dynamic SQL. I carry on with a section on good practices and tips for writing dynamic SQL. I conclude by reviewing a number of situations where you could use dynamic SQL and whether it is a good or bad idea to do it. The article covers all versions of SQL Server from SQL 6.5 to SQL 2008, with emphasis on SQL 2000 and later versions. Contents: Accessing Data from an Application Introducing Dynamic SQL
A First Encounter sp_executesql EXEC()
SQL Injection ± a Serious Security Issue Dynamic SQL and Stored Procedures

The Permission System Caching Query Plans Reducing Network Traffic Encapsulating Logic Keeping Track of what Is Used

Ease of Writing SQL Code Addressing Bugs and Problems

Good Coding Practices and Tips for Dynamic SQL
Use Debug Prints! Nested Strings Spacing and Formatting Dealing with Dynamic Table and Column Names Quotename, Nested Strings and Quotestring QUOTED_IDENTIFIER sp_executesql and Long SQL Strings in SQL 2000 Dynamic SQL in User-Defined Functions Cursors and Dynamic SQL
EXEC() at Linked Server

Common Cases when to (Not) Use Dynamic SQL
SELECT * FROM @tablename SELECT * FROM sales + @yymm UPDATE tbl SET @colname = @value WHERE keycol = @keyval SELECT col AS @myname SELECT * FROM @dbname + '..tbl' SELECT * FROM tbl WHERE col IN (@list) SELECT * FROM tbl WHERE @condition Dynamic Search Conditions Dynamic Crosstab SELECT * FROM tbl ORDER BY @col SELECT TOP @n FROM tbl CREATE TABLE @tbl CREATE TABLE with Unknown Columns Linked Servers OPENQUERY Dynamic Column Widths Dynamic SQL and Maintenance Tasks

Acknowledgements and Feedback Revision History Note: many of the code samples in this text works against the pubs and Northwind databases that ship with SQL 2000 and SQL 7, but not with SQL 2005 and later. You can download these databases from Microsoft's web site.

Accessing Data from an Application
Before I describe dynamic SQL, I like to briefly discuss the various ways you can access data from an application to give an overview of what I'll be talking about in this article. (Note: all through this text I will refer to client as anything that accesses SQL Server from the outside. In the overall application architecture that may in fact be a middle tier or a business layer, but as that is of little interest to this article, I use client in the sake of brevity.) There are two main roads to go, and then there are forks and sub-forks.

1. Send SQL statements from the client to SQL Server. a. Rely on SQL generated by the client API, using options like CommandType.TableDirect and methods like .Update. LINQ falls into this group as well. b. Compose the SQL strings in the client code. i. Build the entire SQL string with parameter values expanded. ii. Use parameterised queries. 2. Perform access through stored procedures. a. Stored procedures in T-SQL i. Use static SQL only. ii. Use dynamic SQL together with static SQL. b. Stored procedures in a CLR language such as C# or VB .Net. (SQL 2005 and later.) Fork 1-a may be good for simple tasks, but you are likely to find that you outgrow it as the complexity of your application increases. In any case, this approach falls entirely outside the scope of this article. Many applications are built along the principles of fork 1-b, and as long as you take the sub-fork 1-b-ii, it does not have to be bad. (Why 1-b-i is bad, is something I will come back to. Here I will just drop two keywords: SQL Injection and Query-Plan Reuse.) Nonetheless, in many shops the mandate is that you should use stored procedures. When you use stored procedures with only static SQL, users do not need direct permissions to access the tables, only permissions to execute the stored procedures, and thus you can use the stored procedure to control what users may and may not do. The main focus for this text is sub-fork 2-a-ii. When used appropriately, dynamic SQL in stored procedures can be a powerful addition to static SQL. But some of the questions on the newsgroups leads to dynamic SQL in stored procedures that are so meaningless, that these people would be better off with fork 1-b instead. Finally, fork 2-b, stored procedures in the CLR, is in many regards very similar to fork 1-b, since all data access from CLR procedures is through generated SQL strings, parameterised or unparameterised. If you have settled on SQL procedures for your application, there is little point in rewriting them into the CLR. However, CLR code can be a valuable supplement for tasks that are difficult to perform in T-SQL, but you yet want to perform server-side.

Introducing Dynamic SQL
In this chapter I will first look at some quick examples of dynamic SQL and point out some very important implications of using dynamic SQL. I will then describe sp_executesql and EXEC() in detail, the two commands you can use to invoke dynamic SQL from T-SQL.

A First Encounter

Understanding dynamic SQL itself is not difficult. Au contraire, it's rather too easy to use. Understanding the fine details, though, takes a little longer time. If you start out using dynamic SQL casually, you are bound to face accidents when things do not work as you have anticipated. One of the problems listed in the introduction was how to write a stored procedure that takes a table name as its input. Here are two examples, based on the two ways to do dynamic SQL in Transact-SQL:
CREATE PROCEDURE general_select1 @tblname sysname, @key varchar(10) AS DECLARE @sql nvarchar(4000) SELECT @sql = ' SELECT col1, col2, col3 ' + ' FROM dbo.' + quotename(@tblname) + ' WHERE keycol = @key' EXEC sp_executesql @sql, N'@key varchar(10)', @key CREATE PROCEDURE general_select2 @tblname nvarchar(127), @key varchar(10) AS EXEC('SELECT col1, col2, col3 FROM ' + @tblname + ' WHERE keycol = ''' + @key + '''')

Before I say anything else, permit me to point out that these are examples of bad usage of dynamic SQL. Passing a table name as a parameter is not how you should write stored procedures, and one aim of this article is to explain this in detail. Also, the two examples are not equivalent. While both examples are bad, the second example has several problems that the first does not have. What these problems are will be apparent as you read this text. Whereas the above looks very simple and easy, there are some very important things to observe. The first thing is permissions. You may know that when you use stored procedures, users do not need permissions to access the tables accessed by the stored procedure. This does not apply when you use dynamic SQL! For the procedures above to execute successfully, the users must have SELECT permission on the table in @tblname. In SQL 2000 and earlier this is an absolute rule with no way around it. Starting with SQL 2005, there are alternatives, something I will come back to in the section The Permission System. Next thing to observe is that the dynamic SQL is not part of the stored procedure, but constitutes its own scope. Invoking a block of dynamic SQL is akin to call a nameless stored procedure created ad-hoc. This has a number of consequences:
y

y y

y

Within the block of dynamic SQL, you cannot access local variables (including table variables) or parameters of the calling stored procedure. But you can pass parameters ± in and out ± to a block of dynamic SQL if you use sp_executesql. Any USE statement in the dynamic SQL will not affect the calling stored procedure. Temp tables created in the dynamic SQL will not be accessible from the calling procedure since they are dropped when the dynamic SQL exits. (Compare to how temp tables created in a stored procedure go away when you exit the procedure.) The block of dynamic SQL can however access temp tables created by the calling procedure. If you issue a SET command in the dynamic SQL, the effect of the SET command lasts for the duration of the block of dynamic SQL only and does not affect the caller.

@params declares the parameters that you refer to in @stmt.0. (Whereas all variables that appear in the SQL string must be declared. nvarchar(4000). You can provide the parameter names for them. so you just keep it as a script that you have a around. Let's look at an example. sp_executesql sp_executesql is a built-in stored procedure that takes two pre-defined parameters and any number of user-defined parameters. int . must be specified positionally. The second parameter @params is optional. Here is what it could look like: DECLARE @tbl @sql @params @count sysname. The rest of the parameters are simply the parameters that you declared in @params. and you pass them as you pass parameters to a stored procedure. just like when you call a stored procedure. Not all parameters you declare must actually appear in the SQL string. A varchar value won't do. The syntax of @params is exactly the same as for the parameter list of a stored procedure. you must specify OUTPUT with the parameter. The block of dynamic SQL has a query plan of its own. or in @params. and contains a batch of one or more SQL statements. many tables have a column LastUpdated. either positional or named. The parameters can have default values and they can have the OUTPUT marker. whereas EXEC() has been around since SQL 6. Beware that you must pass an nvarchar/ntext value (that is. either with a DECLARE inside @stmt. sp_executesql was added in SQL 7. For now I will only give two keywords: SQL Injection and Query-Plan Reuse. This is not something you run as part of the application. @stmt and @params.) Just like @stmt. And. You want to be able to find out how many rows in each table that were modified at least once during a period. in SQL 6. sp_executesql should be your choice 95% of the time for reasons that will prevail.y The query plan for the stored procedure does not include the dynamic SQL. The first parameter @stmt is mandatory. The data type of @stmt is ntext in SQL 7 and SQL 2000. Say that in your database. As you've seen there are two ways to invoke dynamic SQL. sp_executesql and EXEC(). a Unicode value). In the next two sections we will look at these two commands in detail. obviously. but also comes to the rescue in SQL 2000 and SQL 7 when the SQL string exceeds 4000 characters. EXEC() is the sole choice. nvarchar(4000). but something you run as a DBA from time to time. but these names are blissfully ignored. In application code. the data type of @params is ntext SQL 2000 and earlier and nvarchar(MAX) since SQL 2005. and nvarchar(MAX) in SQL 2005 and later. which holds the time a row last was updated. To get a value back from your output parameter.5. but you will use it 90% of the time. Note that the first two parameters. EXEC() is mainly useful for quick throw-away things and DBA tasks.

one optional input parameter. which could cause a syntax error. When I assign the @sql variable. You may note that I've prefix the string literals with N to denote that they are Unicode strings.' + quotename(@tbl) + N' WHERE LastUpdated BETWEEN @fromdate AND ' + N' coalesce(@todate. I also prefix the table name with "dbo.' END DEALLOCATE tblcur I've put the lines that pertain directly to the dynamic SQL in bold face. you might want to use the same name. In this example. Since I left out one variable. technically this is not necessary (as long as . ''99991231'')' SELECT @params = N'@fromdate datetime. ' + N'@cnt int OUTPUT' EXEC sp_executesql @sql. @params. '20060101'. and one output parameter. which is a good habit. you must double it. the dynamic SQL has three parameters: one mandatory input parameter. @count) + ' modified rows. but I wanted to stress that the @cnt in the dynamic SQL is only visible within the dynamic SQL. but @count in the surrounding script. I put the table name in quotename() in case a table name has any special characters in it. You can see that I have declared the @sql and @params variables to be of the maximum length for nvarchar variables in SQL 2000. you may want to make it a routine to declare @sql as nvarchar(MAX). I am careful to format the statement so that it is easy to read. ' + N'@todate datetime = NULL. Overall. I've assumed that this time the DBA wanted to see all changes made after 2006-01-01. which is why I've left out @todate in the call to sp_executesql.DECLARE tblcur CURSOR STATIC LOCAL FOR SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated' ORDER BY 1 OPEN tblcur WHILE 1 = 1 BEGIN FETCH tblcur INTO @tbl IF @@fetch_status <> 0 BREAK SELECT @sql = N' SELECT @cnt = COUNT(*) FROM dbo. In SQL 2005 and later.". whereas @count is not visible there. As @sql and @params are declared as nvarchar. and I leave in spaces to avoid that two concatenated parts are glued together without space in between. as we will see when we look at dynamic SQL and query plans. I will cover this sort of good practices more in detail later in the text. @cnt by name ± the same rules as when you call a stored procedure. Note also the appearance of '' around the date literal ± the rule in T-SQL is that to include the string delimiter in a string. @cnt = @count OUTPUT PRINT @tbl + ': ' + convert(varchar(10). Normally. more about this just below. I must specify the last. Note also that the variable is called @cnt in the dynamic SQL.

In this case. The parameter can be a concatenation of string variables and string literals. you must interpolate them into the string. this is not legal: EXEC('UPDATE STATISTICS ' + quotename(@tbl) + ' WITH FULLSCAN') Best practice is to always use a variable to hold the SQL statement. I used quotename(). but here I've let it suffice with adding brackets. It could look like this: FETCH tblcur INTO @tbl IF @@fetch_status <> 0 BREAK EXEC('UPDATE STATISTICS [' + @tbl + '] WITH FULLSCAN') In the example with sp_executesql. EXEC() EXEC() takes one parameter which is an SQL statement to execute. but it is not uncommon to exceed that limit. If you are on SQL 2000 or SQL 7. @x = 2 If you remove any of the Ns. described just below. this is not an issue. that's the whole story. in case there is a table named Order Details (which there is in the Northwind database). say that you want to run UPDATE STATISTICS WITH FULLSCAN on some selected tables. but cannot include calls to functions or other operators. N'@x int'. you cannot use this data type for local variables. you will need to use EXEC(). Since EXEC only permits string literals and string variables to be concatenated and not arbitrary expressions. but without the many restrictions of ntext. EXEC() is less hassle than sp_executesql. You may wonder why I do not pass @tbl as a parameter as well. column names etc dynamically. In many cases this will do fine. as in this fairly silly example: EXEC sp_executesql N'SELECT @x'.you stick to your 8-bit character set). Since SQL 2005. For very simple cases. you will have to stick to nvarchar(4000). The answer is that you can't. For instance. so the example would better read: FETCH tblcur INTO @tbl IF @@fetch_status <> 0 BREAK SELECT @sql = 'UPDATE STATISTICS ' + quotename(@tbl) + ' WITH FULLSCAN' EXEC(@sql) . you must specify the N. While the parameter is ntext. You can't specify a table name through a variable in TSQL. you will get an error message. Here you can use the new data type nvarchar(MAX) which can hold as much data as ntext. there is no implicit conversion from varchar. Dynamic SQL is just like any other SQL. Thus. there is a limitation with sp_executesql when it comes to the length of the SQL string. when you need to specify things like table names. However. Since sp_executesql is a built-in stored procedure. when you provide any of the strings directly in the call to sp_executesql. Thus.

@sql2 and @sql3 can be 4000 characters long ± or even 8000 characters as EXEC() permits you to use varchar. you need to learn about SQL injection and how you protect your application against it.The fact that you can concatenate strings within EXEC() permits you to make very quick things. a problem for which dynamic SQL is a very good solution. dynamic SQL generated in T-SQL stored procedures. SQL injection is a technique whereby an intruder enters data that causes your application to execute SQL statements you did not intend it to. it is open for SQL injection: CREATE PROCEDURE search_orders @custid nchar(5) = NULL. This is not a line of attack that is unique to MS SQL Server. (I discuss these statements more in detail in my article Granting Permissions Through Stored Procedures. but all RDBMS are open to it. @shipname nvarchar(40) = NULL AS DECLARE @sql nvarchar(4000) SELECT @sql = ' SELECT OrderID. You can. The purpose of the procedure below is to permit users to search for orders by various conditions. CustomerID. EXEC() permits impersonation so that you can say: EXEC(@sql) AS USER = 'mitchell' EXEC(@sql) AS LOGIN = 'CORDOBA\Miguel' This is mainly a syntactical shortcut that saves you from embedding the invocation of dynamic SQL in EXECUTE AS and REVERT. EXEC does not have this limitation. or SQL batches executed from CLR stored procedures. Here is an example. In SQL 2005 and later. when I also show you how you can use EXEC() to pass longer strings than 4000 characters to sp_executesql. but I've cut it down to two to be brief. OrderDate. SQL Injection ± a Serious Security Issue Before you start to use dynamic SQL all over town. which can be convenient at times. A real-life example of such a procedure would have many more parameters. however. (This is. Since you cannot use parameters. but it can lead to poor habits in application code. use INSERT-EXEC to insert the result set from EXEC() into a table. be that SQL statements sent from the client. you cannot as easily get values out from EXEC() as you can with sp_executesql. you can in practice only use 4000 characters in your SQL string with sp_executesql. in SQL 7 and SQL 2000. by the way. As I mentioned. I will show you an example later on. there are situations where this is an enormous blessing. However. since you can say: EXEC(@sql1 + @sql2 + @sql3) Where all of @sql1. ShipName ' + .) SQL 2005 adds a valuable extension to EXEC(): you can use it to execute strings on linked servers. SQL injection is possible as soon there is dynamic SQL which is handled carelessly.) As the procedure is written. I will cover this form of EXEC() in a separate section later in this text.

He then finds out if he needs any extra tokens to terminate the query. Finally he adds a comment character to kill the rest of the SQL string to avoid syntax errors. the attacker knows that there is a vulnerability. because you trust your users. the attack succeeds.Orders WHERE 1 = 1 --' AND ShipName LIKE '' DROP TABLE orders This is a perfectly legal batch of T-SQL. an attacker first tests what happens if he enters a single quote (') in an input field or a URL. But it is not uncommon for web applications to have a general login that runs SQL queries on behalf of the users. the attacker can add users and logins as he pleases. but if you have dynamic table and column names. but if the attacker has achieved sysadmin rights on the server. Mind you. For instance.Orders WHERE 1 = 1 ' IF @custid IS NOT NULL SELECT @sql = @sql + ' AND CustomerID LIKE ''' + @custid + '''' IF @shipname IS NOT NULL SELECT @sql = @sql + ' AND ShipName LIKE ''' + @shipname + '''' EXEC(@sql) Before we look at a real attack. And if this web app logs into SQL Server with sysadmin or db_owner privileges. usually a single quote. he can change that. with sysadmin rights. And if the service account for SQL Server has admin privileges in Windows. A delimiter. affects your dynamic SQL. and a malicious user can take benefit of this. So even if you think that SQL injection is no issue to you. there are more options an attacker could succeed with. so that they can search for Brian O'Brien and Samuel Eto'o. Single quote is the most common character to reveal openings for SQL injection. and then he can add his own SQL statement. @key varchar(10) AS EXEC('SELECT col1. A plain user who runs a Windows application and who logs into SQL Server with his own login. Assume that the input for the parameters @custid and @shipname comes directly from the user and a naïve and innocent user wants to look for orders where ShipName is Let's Stop N Shop. consider this input for @shipname: ' DROP TABLE Orders -- The resulting SQL becomes: SELECT * FROM dbo. (Which is disabled by default on SQL 2005 and later. including the text in red.) Typically. col2. If this yields a syntax error. is not likely to have permissions to drop a table. you still need to read this section. Since there is something called permissions in SQL Server. So this is the starting point. this attack may or may not succeed. the attacker has access into your network far beyond SQL Server through xp_cmdshell.' FROM dbo. he will get a syntax error. Do you see what will happen? Because @shipname includes a single quote. so he enters Let's. col3 FROM ' + @tblname + ' WHERE keycol = ''' + @key + '''') . Take this dreadful version of general_select: CREATE PROCEDURE general_select2 @tblname nvarchar(127). let's just discuss this from the point of view of user-friendliness.

And don't overlook numeric values: they can very well be used for SQL injection. OrderDate. but also luck for someone to find and exploit a hole for SQL injection. Thus. Of course. The procedure search_orders above should be coded as: CREATE PROCEDURE search_orders @custid nchar(5) = NULL.and assume that @tblname comes from a URL. ShipName ' + ' FROM dbo. But remember that there are too many hackers out there with too much time on their hands. You may think that it takes not only skill. and that we will look a little closer at. not EXEC(). it should be confined to reading operations so that users only need SELECT permissions. there is a huge potential for SQL injection. That is. The second point makes the task for the attacker more difficult as he cannot get feedback from his attempts. SQL injection is a serious security issue. Users that log into an application with their own login should normally only have EXEC permissions on stored procedures. CustomerID. the intruder will not be able to do that much harm. @shipname nvarchar(40) = NULL AS DECLARE @sql nvarchar(4000) SELECT @sql = ' SELECT OrderID. is to validate input data in some way. A web site that logs into a database should not have any elevated privileges. but if a supposedly numeric value is directly interpolated into an SQL string in client code. Never let the web site log in as sa! For web applications: never expose error messages from SQL Server to the end user. preferably only EXEC and (maybe) SELECT permissions. There are quite some options that an attacker could use to take benefit of this hole.Orders WHERE 1 = 1 ' IF @custid IS NOT NULL SELECT @sql = @sql + ' AND CustomerID LIKE @custid ' IF @shipname IS NOT NULL SELECT @sql = @sql + ' AND ShipName LIKE @shipname ' . The first point is mainly a safeguard. but in my opinion that is not the right way to go. The most commonly used area for injection attacks on the Internet is probably parameters in URLs and cookies. in a T-SQL procedure use sp_executesql. be very careful how you handle anything that comes into your application from the outside. One approach I seen mentioned from time to time. and you must take precautions to protect your applications against it. so that if there is a injection hole. Always used parameterised statements. Here are are the three steadfast principles you need to follow: y y y Never run with more privileges than necessary. in a T-SQL procedure where the value is passed as an int parameter there is no risk. If you use dynamic SQL. But it is the third point that is the actual protection. Keep in mind that user input comes from more places than just input fields on a form.

Execute Since the main focus of this text is dynamic SQL in T-SQL procedures. there is no opening for SQL injection. @custid. ShipName " & _ " FROM dbo.Orders WHERE 1 = 1 " If custid <> "" Then cmd. In ADO you use ? as a parameter marker. we can always pass all input parameters to the SQL string.Parameters.CommandText = cmd. for instance table and column names.EXEC sp_executesql @sql. we don't need any complicated logic to build the parameter list. CustomerID.Net. adParamInput. but can keep it static. In this case you must enclose all such object names in quotename().CommandText = " SELECT OrderID. and you can only pass parameters that actually appear in the SQL string. In the section Caching Query Plans. It's as simple as that. you will get a completely incomprehensible error message. 5. N'@custid nchar(5). You may think that an even better protection against SQL injection is to use stored procedures with static SQL only.) If you use the SQL Profiler to see what ADO sends to SQL Server. but! It depends on how you call your stored procedures . 40. I will explain this example only briefly.CommandText & " AND CustomerID LIKE ? " cmd. @shipname Since the SQL string does not include any user input. note that since we can include parameters in the parameter list. adWChar. shipname) End If Set rs = cmd.Append cmd. adParamInput. As you may recall. Since this is so important. custid) End If If shipname <> "" Then cmd. _ adVarWChar. The example above was for dynamic SQL in a T-SQL stored procedure. Protection against SQL injection is not the only advantage of using parameterised queries. you will find that it invokes ± sp_executesql. this is true. @shipname nvarchar(40)'.CommandType = adCmdText cmd. In the same vein. This section also includes an example of composing and sending a parameterised SQL statement for SqlClient in VB . OrderDate.CreateParameter("@custid". even if they don't actually appear in the SQL string. here is an example of coding the above in VB6 and ADO: Set cmd = CreateObject("ADODB.Append cmd.Parameters. we will look more in detail on parameterised queries and at a second very important reason to use them.CommandText = cmd. The same advice applies to SQL generated in client code or in a CLR stored procedure.CommandText & " AND ShipName LIKE ? " cmd. Yes.CreateParameter("@shipname".ActiveConnection = cnn cmd.Command") Set cmd. that I will return to in the section Good Coding Practices and Tips for Dynamic SQL. you cannot pass everything as parameters to dynamic SQL. By the way. (If you specify too many parameters.

whereas other are unaffected. where I discusses both certificates and impersonation in detail. But you . you need to call your procedure with the command type adCmdStoredProc and use . I will also look at what happens when you use dynamic SQL in a stored procedure.CreateParameter to specify the parameters. this can be addressed by signing a procedure that uses dynamic SQL with a certificate. and they cannot perform updates that violate business rules. By specifying adCmdStoredProc. This method is easier to use. the application performs all access through stored procedures that retrieve and update data in a controlled way. I will look a little closer at the advantages with using stored procedures over sending SQL statements from the client.from the client. Instead I've written a separate article about them. but it is also more efficient. users do not have permissions to access tables directly. Thus the chain is broken. and I said that in many shops all data access is through stored procedures. Similar measures apply to other client APIs. As I have already mentioned. all APIs I know of supply a way to call a stored procedure through RPC. would take up too much space here. If you write CLR procedures that perform data access. row-level security schemes and system monitoring. You associate the certificate with a user. my strong recommendation is to use certificates. In this section. and I also take a closer look on ownership chaining. The Permission System Historically. Describing these methods more closely. Giving Permissions through Stored Procedures. The reason for this is very simple: the block of dynamic SQL is not a procedure and does not have any owner. ownership chaining does not work when you use dynamic SQL. so that users only get to see data they have access to. SQL 2005 and later In SQL 2005 and later versions of SQL Server. through a mechanism known as ownership chaining. Ownership chaining never applies since all data access in a CLR procedure is through dynamic SQL. you call the stored procedure through RPC. which not only protects you against SQL injection. but has side effects that can have unacceptable consequences for auditing. For this reason. and show that you lose some of the advantages with stored procedures. In a lockeddown database. I presented various strategies for data-access for an application. using stored procedures has been the way to give users access to data. Instead. the same is true for them. Dynamic SQL and Stored Procedures In the introduction. you are back on square one and you are as open to SQL injection as ever. A second method is to use the EXECUTE AS clause to impersonate a user that has been granted the necessary permissions. If you compose an EXEC command into which you interpolate the input values. This works as long as the procedure and the tables have the same owner. and grant that user (which is a user that cannot log in) the rights needed for the dynamic SQL to execute successfully. In ADO. Remote Procedure Call. typically dbo (the database owner).

Any use of dynamic SQL requires that the users have direct permissions on the accessed tables. some ways to arrange so that users only have access to the data through the application. or it is invalidated for some reason.. the application authenticates the users outside SQL Server and logs into SQL Server on their behalf with a proxy login. the network is configured so that they cannot access SQL Server from their regular computers. Users log into the terminal server which is set up so that all they can do is to run this application. With "application proxies". If a query needs to run for four . If your security scheme precludes giving users permissions to access tables directly. UPDATE and DELETE rights on tables only to permit dynamic SQL in some occasional procedure. Users log into SQL Server but have no permissions on their own beyond the database access. you cannot use dynamic SQL. and next time you run the query. SQL 2000 and earlier On SQL 2000 there is no way to combine dynamic SQL with the encapsulation of permissions that you can get through stored procedures. the plan is reused. (Why this happens falls outside the scope of this article. Instead. In Giving Permissions. SQL Server builds a query plan for it ± or as the terminology goes ± it compiles the query. and do not grant more permissions than needed. Furthermore. All require you to change the application architecture or infrastructure..can use certificates or impersonation to avoid having to give users direct permissions on the tables. This proxy login impersonates the users in SQL Server. "application proxies" and Terminal Server. the application activates the application role by sending a password somehow embedded into it. I discuss these two methods a little further. For all these methods.) The reuse of cached query plans is very important for the performance of queries where the compilation time is in par with the execution time or exceeds it. and this application role has the permissions needed. All and all. Application roles were introduced in SQL 7. There are however. Caching Query Plans Every query you run in SQL Server requires a query plan. the application is their only way to the data. It is that plain and simple. application roles. they cannot log into SQL Server outside the application. and thus their permissions apply. I strongly recommend against granting users INSERT. since the users do not have any login on their own. Depending on the sensitivity of the data in the application. there are three alternatives. The query plan stays in cache until it's aged out because it has not been used for a while. it may be acceptable to give the users SELECT permissions on the tables (or on some tables) to permit the use of dynamic SQL. Thus. The final possibility is to put the application on Terminal Server. SQL Server saves the plan in cache. keep in mind about SQL injection. When you run a query the first time. However. so it is nothing you introduce at whim..

the use of dynamic SQL nullified the benefit with stored procedures in this regard. '19980201'.Quantity) Orders O [Order Details] OD ON O. the same plan can be reused even when the input changes.OrderID AND OD2.OrderID O.OrderID GROUP The query returns the total order amount for the orders in February 1998 that contained the product Lakkalikööri. the plan will be reused.and case-sensitive. 76 The principle for cache lookup is the same as for a non-parameterised query: SQL Server hashes the query text and looks up the hash value in the cache.OrderID = OD2. if you instead use sp_executesql to run your query with parameters: DECLARE @sql nvarchar(2000) SELECT @sql = 'SELECT O.and space-sensitive fashion. Up to SQL 6.OrderDate BETWEEN '19980201' AND '19980228' EXISTS (SELECT * FROM [Order Details] OD2 WHERE O. SUM(OD. the plan is not reused.[Order Details] OD2 WHERE O.UnitPrice * OD.Orders O JOIN dbo. Since the cache lookup is by a hash value computed from the query text.OrderID' EXEC sp_executesql @sql.5.UnitPrice * OD. . it is not unlikely that next time you want to run the query for a different product. But since the parameter values are not part of the query text.ProductID = 76) BY O. More importantly. Say that you send this query from the client.OrderID = OD. still in a case.[Order Details] OD ON O. Starting with SQL 7. @prodid int'. that included dynamic SQL as well.OrderID. '19980228'.OrderID = OD2.OrderDate BETWEEN @from AND @to AND EXISTS (SELECT * FROM dbo. SQL Server also caches the plans for bare statements sent from a client or generated through dynamic SQL. SQL Server will put the plan into the cache. or execute it with EXEC(): SELECT FROM JOIN WHERE AND O. On the other hand.OrderID WHERE O. Loose batches of SQL were compiled each time. Thus in SQL 6. the cache is space. All this changes.OrderID. particularly if the query is executed over and over again. N'@from datetime.minutes. @to datetime. SUM(OD.5 the only plans there were put into the cache were plans for stored procedures. or a different period. But only if it is exactly the same query. it does not matter much if the query is recompiled for an extra second each time. there is a huge gain with the cached plan.OrderID = OD. Thus. and next time you run this query.ProductID = @prodid) GROUP BY O.OrderID AND OD2. if you add a single space somewhere. if the execution time of the query is 40 ms but it takes one second to compile the query. And since the query plan for dynamic SQL is not part of the stored procedure.Quantity) FROM dbo.

UnitPrice * OD. it follows that if you use dynamic SQL with EXEC() you lose an important benefit of stored procedures whereas with sp_executesql you don't. and if you leave it out in just a single place in the query. user1 cannot share cache entry with a user different default schema.OrderID = OD2.[Order Details] OD2" & _ " WHERE O. Do you see that I've prefixed all tables in the query with dbo? There is a very important reason for this. Microsoft still recommends that you do. SQL Server must first check if there is a table user1. (And still with the caveat that the cache lookup is space. in SQL 2005.Quantity)" & _ " FROM dbo. you will get as many entries in the cache for the query as there are users running it.and case-sensitive.OrderID" & _ . Users can have different default schema. if default schema for user1 is user1. or they failed to prefix tables with dbo. users with different default schema can share the same query plan. In the section on SQL Injection.OrderID = OD.. Here is an example with VB . but it seems to be a bad idea to rely on it.Orders could appear on the scene at any time.OrderDate BETWEEN @from AND @to" & _ " AND EXISTS (SELECT *" & _ " FROM dbo. It's easy to forget that dbo. At least in theory. Furthermore. Thus. Presumably.) Most client APIs implement parameterised queries by calling sp_executesql under the covers. In fact.CommandType. Yes.OrderID. you may inadvertently have different spacing or inconsistent use of case. since the cache lookup is by a hash value computed from the query text. I would assume that this is somewhat more expensive than looking up a stored procedure. I included an example on how to do parameterised queries with ADO and VB6.Text cmd.Orders.Data.OrderID" & _ " WHERE O. can lead to serious performance degradation.. heavy use of dynamic SQL.Orders. From what I have said here. and this users runs a query that goes "SELECT . but even if you don't. And this is not restricted to the SQL statement. Some of my MVP colleagues have observed systems with lots of memory (> 20 GB) when the plan cache has been so filled with plans for SQL statements. If you instead use stored procedures. So far. whereas parameterised queries can be as efficient as stored procedures if you remember to always prefix the tables with dbo. under extreme circumstances. FROM Orders".Net and SqlClient: cmd. But in this regard there is very little difference to SQL statements sent from the client.CommandType = System. the applications in question either did not use parameterised queries at all. it is perfectly possible that all users have dbo as their default schema. Since user1. that there have been hash collisions galore.and case-sensitive.[Order Details] OD ON O. Recall also that the cache is space. so if you generate the same query in several places. it is not equally important to prefix tables with dbo. and the cache lookup alone could take several seconds. the parameter list is as much part of the cache entry.To make this really efficient there is one more thing you need to observe. SUM(OD. before it looks for dbo.Orders O " & _ " JOIN dbo. and up to SQL 2000. The same rules apply: unparameterised statements are cached but with little probability for reuse. all users had a default schema equal to their username. or SQL statements generated in CLR procedures.CommandText = _ " SELECT O. I've only talked about dynamic SQL in stored procedures.

it seems. With simple parameterisation. Starting with SQL 2005 you can force a query to be recompiled each time it is executed by adding OPTION (RECOMPILE) to the end of the query. And if that recompilation slashes the execution time from forty minutes to four.Value = 76 In contrast to ADO.Orders WHERE CustomerID = @P1 so if next time you submit BERGS instead of ALFKI. Autoparameterisation comes in two flavours: simple and forced. SqlClient uses names with @ for parameters.. OrderDate FROM dbo. in my opinion. SqlDbType. For the sake of completeness.Add("@to". Recall what I said in the beginning of this section. I should mention that SQL Server is able to auto-parameterise queries. one second extra for compilation is not a big deal. SqlDbType. mainly a setting to . OrderDate FROM dbo. it may in fact be better to interpolate critical parameters into the query string when you need to force recompilation each time.Datetime) cmd.ProductID = @prodid)" & _ cmd. The syntax for defining parameters is similar to ADO. Instead.Parameters.Parameters.Value = "1998-02-28" cmd.Int) cmd..Value = "1998-02-01" cmd. please learn how to use parameterised commands with it. with some inconsistency.Orders WHERE CustomerID = N'ALFKI' SQL Server may recast this as SELECT OrderID. auto-parameterisation happens only with very simple queries. SqlDbType. Yes. so I will not go into details on how the Parameters collection works.Parameters.Datetime) cmd.Parameters("@to"). If you submit: SELECT OrderID. and worst of all opening their database to SQL injection. But if the request is for the entire year.Parameters("@prodid"). there is a tone of desperation in my voice. Say that you have a query where the user can ask for data for some time span." " GROUP AND BY O. With forced parameterisation. Most queries benefit from cached parameterised plans. and. I don't know how many posts I've seen on the newsgroups over the years where people build their SQL strings by interpolating the values from input fields into the SQL string. there is a huge gain. the same index would be a disaster. and thereby degrading the performance of their application. . SQL Server parameterises all queries that comes its way (with some exceptions documented in Books Online). the query plan will be reused.Add("@prodid". I refer you to MSDN where both SqlClient and ADO are documented in detail. If the user asks for a summary for a single day. and just when you thought you were safe.Add("@from". but not all do. but not identical. that if the query is going to run for four minutes. Simple is the default and is the only option on SQL 2000 and earlier. Whatever client API you are using. and a table scan is better.Parameters("@from"). there is a good non-clustered index that can be used for a sub-second response time. This article is long enough. Forced parameterisation is. On SQL 2000 and earlier. I need to turn this upside down.OrderID" OD2. and thus you can still use sp_executesql to get the best protection against SQL injection.

OrderDate. Mgmt Studio emits a couple of queries with the procedure name embedded.) They say seeing is believing. (And that Microsoft can not use their own products properly. C.) If you run SQL Server on your local machine. Once scripting is complete. Select all procedures. First create this database: CREATE DATABASE many_sps go USE many_sps go DECLARE @sql nvarchar(4000). but they have nothing to do with the topic of this article. and then use Task Manager to see how much physical memory SQL Server uses in the two cases. total = SUM(Quantity * UnitPrice) FROM Northwind. but on my machine it took 90 seconds and at the same time SQL Server grabbed over 250 MB of memory. you will see that for each procedure. How long time this takes depends on your hardware. That is..1 END Then in SQL Server Management Studio 2005. issue this command: ALTER DATABASE many_sps SET PARAMETERIZATION FORCED and redo the operation. This particular issue have been addressed in SQL Server Management Studio 2008. (But in the situation you really a want a new query plan each time. cnt = COUNT(*). Then from the context menu select to script them as CREATE TO to a new query window. That difference lies entirely in the plan cache.OrderID = @orderid' EXEC(@sql) SELECT @x = @x .OrderID WHERE O. you can stop and restart SQL Server before the two scripting operations. This demonstrates that the difference between parameterised and unparameterised can be dramatic. no parameterised statements.OrderID = O.Orders O JOIN Northwind.. If you use the Profiler to see what Mgmt Studio is up to. you may have to verify that it doesn't happen when you don't want to.CustomerID = C.. On my machine scripting now completed in five seconds!.cover up for poorly designed third-party application that uses unparameterised dynamic SQL.OrderID. you can see this from one more angle. O. if you have SQL 2005.total FROM Northwind.CustomerID JOIN (SELECT OrderID.cnt. Prodcnt = OD.CustomerID.[Order Details] GROUP BY OrderID) AS OD ON OD. O. SSMS 2008 has its own scripting issues.Customers C ON O. Totalsum = OD.CompanyName. Here is a demo that you can try on yourself. . For your own development you should not rely on any form of auto-parameterisation. press F7 navigate down to the list of stored procedures. @x int SELECT @x = 200 WHILE @x > 0 BEGIN SELECT @sql = 'CREATE PROCEDURE abc_' + ltrim(str(@x)) + '_sp @orderid int AS SELECT O.

I'm here assuming that most of your procedures use static SQL only. But there are also people who like to see the database as a unintelligent container of data. but one of good programming practice and modularising your code. it depends a little on what you put into those stored procedure. Rather than sending a 50-line query over the network.) In this case. If you drop and recreate a table. and it's immaterial whether they use dynamic SQL or not. the dividing line goes between sending SQL from the client or running stored procedures. the only container of logic available is stored procedures. Then again.sql_dependencies in SQL 2005 and later. sometimes there is no other application than Query Analyzer or SQL Server Management Studio. Then again. or invoke dynamic SQL does not matter. If all your stored procedures generate dynamic SQL. You still get the gains of reduced network traffic.) In this case. you may need to know where a certain table or column is referenced. then you are probably better off in this regard to do it all in client code. and how it looks on the inside does not matter. nor does it matter if it is a CLR procedure. (Typically this would be tasks that are run by an admin. By using stored procedures.) I say may. the arguments for using stored procedures for encapsulation may not be equally compelling. Encapsulating Logic This is not a question of security or performance. and in this case there is no dispute that you should use stored procedures to encapsulate your logic. although it may require some careful use of your client API. you don't have to bog down your client code with the construction of SQL statements.sql_expression_dependencies. This gets more significant if the computation requires several queries. Keeping Track of what Is Used In a complex system with hundreds of tables. sys. If the stored procedures use static SQL only.Reducing Network Traffic Another advantage with stored procedures over SQL sent from the client is that less bytes travel the network. I am of the school that the business logic should be where the data is. possibly with logic in between. The stored procedure is still a container for some piece of logic. only to travel back in the next moment. (You can use temp tables from outer layers as well. because it is very difficult to maintain complete dependency information in SQL Server. Myself. If all logic is outside the database. you only need to pass the name of a stored procedure and a few parameters. this could mean that data has to travel up to the client. If all access to tables is from static SQL in stored procedures. Nothing of this changes if you use dynamic SQL in your stored procedures. you may be able find all references by using the system stored procedure sp_depends or query a system table directly. With stored procedures you can use temp tables to hold intermediate results. (sysdepends in SQL 2000. and who prefer to have the business logic elsewhere. In SQL 2008 there is also sys. You could just as well employ careful programming practices in your client language and send SQL strings. because you are considering changing or dropping it. all dependency . In this case.

or SQL generated by CLR stored procedures . VBScript ± all use the double quote (") as their string delimiter. which makes programming far more complex. If not. and which eventually becomes unbearable complex and inefficient because of all the legacy baggage it's carrying around. if you use stored procedures with static SQL only. that is only run in odd cases and not covered in your test suite. With dynamic SQL. Ease of Writing SQL Code One distinct advantage of writing stored T-SQL procedures is that you get a syntax check directly.you lose this opportunity. It has to be admitted that the strength of this argument is somewhat reduced by the fact that TSQL is not too industrious on reporting semantic errors. While the main dividing line here is between static SQL and any form of dynamic SQL. an ampersand and an underscore for continuation. but as the procedure text there is chopped into 4000char slices. It sure does not serve to make coding easier. You are relieved from all this hassle. dynamic SQL in T-SQL procedures. Another side of this coin is that when you write dynamic SQL.definition using SQL. and to include a single quote into the string you need to double it. In any case. You can even search the column sys. you may end up with a database where no one ever dares to drop or change a column or a table. Your SQL code is a string delimited by single quotes('). In SQL 2000 you can search syscomments. (In the section Good Coding Practices and Tips for Dynamic SQL. If you throw dynamic SQL into the mix ± be that SQL sent from client. a trivial syntax error may not show up until run time.) The most commonly used client languages with T-SQL . we will look a little closer on how to deal with this problem. an occasional stored procedure that uses dynamic SQL is not likely cause the Armageddon I pictured above.Visual Basic. be that misspellings or temp tables created within the procedure. as there is less code to search. . Even if you test your code carefully.sql_modules. Then again. SQL Server will not examine queries in stored procedures. you embed the SQL code into strings. But it is a good argument for being restrictive with dynamic SQL in any form. You can easily get lost in a maze of quotes if you don't watch out. for this to be a very important reason to use stored procedures. What I do myself is to regularly build an empty database from our version-control system. so dynamic SQL in client code or CLR stored procedures is less prone to that particular problem. Because of deferred name resolution. I know that I can trust the dependency information in that database. this may work. C++. Nevertheless. and if the construction of dynamic SQL is confined to some well-defined set of modules. Available since SQL 2005. dynamic SQL in T-SQL stored procedures is probably the least harmful. C#. The alternative is to employ brute-force search.information for the table is lost. and since our build tool loads all tables before any stored procedure or trigger. SQL Server does report sufficiently many errors. this is less reliable. or some variation of a query. where one or more tables are missing. and this string may include strings itself. there may be some query. in VB you don't have multi-line strings. so at the end of each line you have to have a double quote.

with an application that generates SQL in the client.) In this case. or if it also uses dynamic SQL. and the fix is trivial. Which any DBA that knows how to use Google can do. For CLR procedures it depends on many objects you have in your assemblies. one of the strongest arguments for stored procedures today may be that they permit you to quickly address bugs and performance problems in the application. he may be able to fix that by adding an index hint. and the combination of dynamic SQL and user-defined functions. In this section. In contrast. and be difficult to read. (I should add that SQL 2005 offers a new feature that permits the DBA to change the plan for a query without altering the code. This feature has been further enhanced in SQL 2008. installing a new version of a CLR procedure is as simple as replacing a T-SQL procedure. If your application uses stored procedures. I will also discuss some special cases: how you can use sp_executesql for input longer than 4000 chars in SQL 2000. (If you encrypt your procedures. we will look at how to avoid this. If you just go ahead. If you have one assembly per object. This means that before the fix can be put into production. his hands will be tied. Say that you generate SQL statements in your application. Of course. if you are an ISV and you ship a product that the customer is supposed administer himself. but this is best controlled through license agreements. the module will have to go through QA and testing. if a procedure runs unacceptably slow. as long as he is able to find a way to decrypt them. To fix it. by adding a plan guide. which is likely to contain other code that also has changed since the module was shipped. as an ISV you may not want your customers to poke around in your code. and that there is an error in it. you may be able to deploy a fix into production within an hour after the problem was reported. For instance. troubleshoot and maintain. This difference is even more emphasised. your code can become very messy. you need to build a new executable or DLL. it does not matter whether the stored procedure uses static SQL only. you should always include a @debug parameter: . Use Debug Prints! When you write a stored procedure that generates dynamic SQL. even less to change it.Addressing Bugs and Problems Somewhat surprisingly. and I refer to Books Online for details.) Good Coding Practices and Tips for Dynamic SQL Writing dynamic SQL is a task that requires discipline to avoid losing control over your code. and how to use dynamic SQL with cursors. Or that it simply performs unbearably slow. On the other hand. if the problem is in a stored procedure. the DBA can still change them. You may also prefer to ship your procedures WITH ENCRYPTION to protect your intellectual property. a DBA may be able to address problems directly without opening a support case. This is quite an advanced feature.

there are situations when you need to deal with nested quotes even with sp_executesql. If you work with dynamic SQL. Once the SQL code is slapped in your face. So always include a @debug parameter and a PRINT! Nested Strings As I've already mentioned.. And even when you do.. @debug bit = 0 AS . Spacing and Formatting Another thing to be careful with is the spacing as you concatenate the parts of a query. col3 FROM ' + @tblname + ' WHERE keycol = ''' + @key + '''') (Again. For instance. earlier in this article. I showed you the procedure general_select2. However. ''99991231'')' We will look at some tips of dealing with nested strings later in this section. it can get a lot worse. it can be very confusing. it can be very difficult to spot the error only by looking at the code that constructs the SQL. one problem with dynamic SQL is that you often need to deal with nested string delimiters. Here it is again: CREATE PROCEDURE general_select2 @tblname nvarchar(127). I like to emphasise that this sort of procedure is poor use of dynamic SQL. col2. col2. Obviously. I had this code: N' WHERE LastUpdated BETWEEN @fromdate AND ' N' coalesce(@todate. IF @debug = 1 PRINT @sql When you get a syntax error from the dynamic SQL. So those four consecutive single quotes ('''') is a string literal with the value of a one single quote ('). col3 FROM' + @tblname + ' WHERE keycol = ''' + @key + '''') .CREATE PROCEDURE dynsql_sp @par1 int. and you may not even discern where it comes from.. This is a fairly simple example. @key varchar(10) AS EXEC('SELECT col1. you must learn to master nested strings. the error is much more likely to be apparent to you.) SQL is one of those language where the method to include a string delimiter itself in a string literal is to double it. . For instance. Here is an example where it goes wrong: EXEC('SELECT col1. in this case you can easily escape the mess by using sp_executesql instead ± yet another reason to use parameterised statements. in the beginning of this article..

but you must interpolate it into the SQL string. As I've said. col3 are missing. good formatting is essential when working with dynamic SQL. and in the case of a syntax error the line number in the error message may guide you. so in contrast to VB. col1. col2. And. T-SQL permits you to embed newlines in string literals (as testified by the example above). col2. If the code looks like this: SELECT @sql =' SELECT col1. because FROMfoo is a column alias to col3. . And since you know that the table you passed to the procedure has these columns you will be mighty confused. col3 ' + ' FROM ' + @tblname + ' WHERE keycol = ''' + @key + '''') As you see. you cannot pass a table or a column name as a parameter to sp_executesql. Dealing with Dynamic Table and Column Names Passing table and column names as parameters to a procedure with dynamic SQL is rarely a good idea for application code. col2. but when you run it. This is also a good example why you should use debug prints. I have a space after the opening single quote on each line to avoid syntax problems due to missing spaces. even if there is no FROM clause. this error could not occur at all. col3 FROMfoo WHERE keycol = 'abc' This is not a syntax error. though. had we included the dbo prefix. It could be that bad it comes from user input. An advantage of this is that your debug PRINT is easier to read. col2. You may prefer.See that there is a space missing after FROM? When you compile the stored procedure you will get no error. (It can make perfectly sense for admin tasks). (Obviously. you will be told that the columns keycol. yes. assuming the parameters foo and abc: SELECT col1. to have a string terminator on each line. Try to write the query as you would have written it in static SQL. you get an error for that. as a matter of routine. you don't need a string delimiter on each line. col3 FROM' + @tblname + ' WHERE keycol = ''' + @key + '''' IF @debug = 1 PRINT @sql EXEC(@sql) It would be much easier to find the error by running the procedure with @debug = 1.) Overall. it's legal to use a WHERE clause. and then add the string delimiters outside of that. But this is the actual code generated. But since the columns cannot exist out of the blue. A tip in such case is to do something like this: EXEC(' SELECT col1. Still you should protect it against SQL injection.

so if you have a really crazy table name like Left]Bracket.' + quotename(@tblname) + ' WHERE keycol = @key' IF @debug = 1 PRINT @sql EXEC sp_executesql @sql. I'm prefixing the table name with dbo. Here is an example. Thus. quotename() takes care of nested delimiters. '''') Say that @custname has the value D'Artagnan. @debug bit = 0 AS DECLARE @sql nvarchar(4000) SET @sql = 'SELECT col1. The default for the second parameter is [].To this end. This part of the dynamic SQL becomes: AND custname = 'D''Artagnan' . including single quotes. If you work with different schemas. you can use quotename() to protect yourself against SQL injection by help of this function. Note that when you work with names with several components.) While general_select still is a poor idea as a stored procedure. col2. if you for some reason prefer to use EXEC(). here is nevertheless a version that summarises some good coding virtues for dynamic SQL: CREATE PROCEDURE general_select @tblname nvarchar(128). b.Orders]. each component should be quoted separately. N'@key varchar(10)'. quotename() will return [Left]]Bracket]. you should use the built-in function quotename() (added in SQL 7). quotename('dbo. and the second is a pair of delimiters to wrap the string in. best practice is to add dbo in the dynamic SQL and only pass the table name. I'm wrapping @tblname in quotename(). pass the schema as a separate parameter. Nested Strings and Quotestring The main purpose of quotename() is to quote object names. But you can specify other delimiters as well. As long as you only work with the dbo schema. which means that any single quote in the input is doubled. IF @custname IS NOT NULL SELECT @sql = @sql + ' AND custname = ' + quotename(@custname. (Although you could use the built-in function parsename() to split up a @tblname parameter in parts. o and a dot. quotename() takes two parameters: the first is a string. quotename('Orders') returns [Orders]. There is a @debug parameter. Quotename. @key = @key y y y y I'm using sp_executesql rather than EXEC(). @key varchar(10). col3 FROM dbo. which is why the default for the second parameter is brackets. but that is a table in an unknown schema of which the first four characters are d. Thus.Orders') returns [dbo.

SQL 6. @key key_type. if the setting QUOTED_IDENTIFIER is OFF. So with quotename() and quotestring(). so you are a bit out of luck there.) QUOTED_IDENTIFIER Another alternative to escape the mess of nested quotes. A remedy is this user-defined function: CREATE FUNCTION quotestring(@str nvarchar(1998)) RETURNS nvarchar(4000) AS BEGIN DECLARE @ret nvarchar(4000). (I should add that I got the suggestion to use quotename() or a user-defined function from SQL Server MVP Steve Kass. replace 1998 and 4000 with MAX. but the preferred setting is ON. you don't. col2. Nevertheless. to make it work for any string length.There is a limitation with quotename(): its input parameter is nvarchar(128). whereas with parameterised commands. you can do this: CREATE PROCEDURE general_select @tblname nvarchar(127). do we have as good protection against SQL injection as we have with parameterised commands? Maybe. @sq. col3 FROM dbo. I don't know of any way to inject SQL that slips through quotename() or quotestring(). but if you are aware of the caveats. Here is an example of using this function: IF @custname IS NOT NULL SELECT @sql = @sql + ' AND custname = ' + dbo. Thus.quotestring(@custname) The result is the same as above. you are interpolating user input into the SQL string.5 does not have replace(). To wit. The default for this setting depends on context. so it does not handle long strings. @sq + @sq) RETURN(@sq + @ret + @sq) END This version is for SQL 2000. you would have to implement quotestring as a stored procedure. On SQL 7. @debug bit = 0 AS DECLARE @sql nvarchar(4000) SET @sql = 'SET QUOTED_IDENTIFIER OFF SELECT col1. this is not a first-rate alternative. @sq char(1) SELECT @sq = '''' SELECT @ret = replace(@str. On SQL 2005 and later. and it must be ON in order to use XQuery. is make use of the fact that T-SQL actually has two string delimiters.' + quotename(@tblname) + ' WHERE keycol = "' + @key + '"' IF @debug = 1 PRINT @sql . indexed views and indexes on computed columns. you can also use double quotes(") as a string delimiter.

since you cannot use longer SQL strings than 4000 characters. there is actually a workaround.) If you want to use sp_executesql when your query string exceeds this limit to make use of parameterised query plans. N''@state char(2). @cnt int OUTPUT''. (On SQL 2005 and later. it does not have any limitation in size. since you are not protected against SQL injection (what if @key includes a double quote?). But it would be OK to do for some sysadmin task (where SQL injection is not likely to be an issue). @sql2 nvarchar(4000). @mycnt int SELECT @state = 'CA' SELECT @sql1 = N'SELECT @cnt = COUNT(*)' SELECT @sql2 = N'FROM dbo. so by itself. The single quotes are for the SQL string and the double quotes are for the embedded string literals. N''@state char(2)''. you should use nvarchar(MAX) to avoid this problem.authors WHERE state = @state' EXEC('EXEC sp_executesql N''' + @sql1 + @sql2 + '''. @state = ''' + @state + '''') This works. and it may be the best way to go on SQL 6. All and all. @state char(2). @state char(2) SELECT @state = 'CA' SELECT @sql1 = N'SELECT COUNT(*)' SELECT @sql2 = N'FROM dbo. because the @stmt parameter to sp_executesql is ntext. You can even use output parameters by using INSERT-EXEC. @cnt = @cnt OUTPUT SELECT @cnt') SELECT @mycnt = cnt FROM #result . sp_executesql and Long SQL Strings in SQL 2000 There is a limitation with sp_executesql on SQL 2000 and SQL 7. you can wrap sp_executesql in EXEC(): DECLARE @sql1 nvarchar(4000).5.authors WHERE state = @state' INSERT #result (cnt) EXEC('DECLARE @cnt int EXEC sp_executesql N''' + @sql1 + @sql2 + '''. @state = ''' + @state + '''. this is an inferior method to both sp_executesql and quotestring(). To wit. the code is much easier to read. @sql2 nvarchar(4000). as in this example: CREATE TABLE #result (cnt int NOT NULL) DECLARE @sql1 nvarchar(4000).EXEC(@sql) Since there are two different quote characters.

. so that you don't exit the procedure without deallocating the cursor. OPEN @my_cur'. the dynamic SQL is its own scope. as in this example: DECLARE @my_cur CURSOR EXEC sp_executesql N'SET @my_cur = CURSOR STATIC FOR SELECT name FROM dbo. (Because. but people often ask about using dynamic SQL with cursors. FROM tbl WHERE dbo. Since you can do anything from dynamic SQL.MyUdf(somecol) = @value and MyUdf performs data access. Dynamic SQL in User-Defined Functions This very simple: you cannot use dynamic SQL from used-defined functions written in T-SQL. Cursors and Dynamic SQL Not that cursors are something you should use very frequently. and in SQL 2000 there is no way out. In SQL 2005 and later. (You are safe-guarded. you have to put the entire DECLARE CURSOR statement in dynamic SQL: SELECT @sql = 'DECLARE my_cur INSENSITIVE CURSOR FOR ' + 'SELECT col1. Anthony Faull pointed out to me that you can achieve this with cursor variables. as you know by now. Recall that all data access from the CLR is dynamic SQL. col2. I've seen more than one post on the newsgroups where people have been banging their head against this.) A word of warning though: data access from scalar UDFs can often give performance problems. There is however a way to use locally-scoped cursors with dynamic SQL. so that if you perform an update operation from your function. you can use the cursor in a normal fashion. This is because you are not permitted do anything in a UDF that could change the database state (as the UDF may be invoked as part of a query). you could implement your function as a CLR function. But if you want to use dynamic SQL in a UDF. you will get caught. it is important to understand that you must use a global cursor. as a local cursor will disappear when the dynamic SQL exits. col3 FROM ' + @table EXEC sp_executesql @sql You may be used to using the LOCAL keyword with your cursors. You cannot say DECLARE CURSOR EXEC(). you have more or less created a hidden cursor.You have my understanding if you think this is too messy to be worth it. However. You must be extra careful with error-handling though.sysobjects. If you say SELECT .. so I give an example for the sake of completeness. back out and redo your design. You have hit a roadblock. . including updates.) Once you have declared the cursor in this way. it is obvious why dynamic SQL is not permitted.

sysobjects') AT SQL2K SQL2K is here a linked server that has been defined with sp_addlinkedserver. When passing a parameter. (I have to confess I have never seen any use for cursor variables until Anthony Faull was kind to send me this example. and could it be composed dynamically or be entirely static. This could be another instance of SQL Server. The SQL could be a single query or a sequence of statements.) As with regular EXEC(). just like named cursors. you can specify AS USER/LOGIN to use impersonation: EXEC('SELECT COUNT(*) FROM ' + @db + '. and OLE DB uses ? as the parameter marker. The confuse matters. Unfortunately. SQL 2005 does not ship with Northwind. but it could also be an Oracle server. you can pass them as a parameters. as seen by this example: EXEC('SELECT COUNT(*) FROM ' + @db + '. N'VINET') AT SQL2K SELECT @cnt Note here that the parameter values must appear in the order the parameter markers appear in the query. The syntax is simple. You can run this: DECLARE @cnt int EXEC('SELECT ? = COUNT(*) FROM Northwind. You may ask why the inconsistency with a different parameter marker from sp_executesql? Recall that linked servers in SQL Server are always accessed through an OLE DB provider.dbo. but you have a linked server set up to an instance of SQL 2000 with Northwind. that you cannot do with EXEC() on a local server: you can use parameters. and you are dying to know how many orders VINET had in the Northwind database. both for input and output.dbo. and. instead you use question marks (?) as parameter holders.N'@my_cur cursor OUTPUT'. Say that you are on an SQL 2005 box. you can either specify a constant value or a variable.Orders WHERE CustomerID = ?'. but there is an @ in front. you don't use parameters with names starting with @. a convention inherited from ODBC. Active directory or whatever.sysobjects') AS USER = 'davidson' AT SQL2K .dbo. There is one thing that you can do with EXEC() at a linked server. as you see from the example. @cnt OUTPUT. @my_cur OUTPUT FETCH NEXT FROM @my_cur You refer to a cursor variable. (Not all RDBMS use @ for variables.) EXEC() at Linked Server A special feature added in SQL 2005 is that you can use EXEC() to run pass-through queries on a linked server. OLE DB translates that parameter marker as is appropriate for the data source on the other end. an Access database.

You will see that sometimes dynamic SQL is a good choice. But it is just that when it comes to database objects. VB etc where parameterisation is a good thing. SELECT * FROM @tablename A common question is why the following does not work: CREATE PROCEDURE my_proc @tablename sysname AS SELECT * FROM @tablename As we have seen. far too many examples use EXEC() without any thought of query plans. each table is unique. (The login to use on the remote server can be defined with sp_addlinkedsrvlogin. One camp appears to be people who are new to SQL programming. but it should also be clear that we gain none of the advantages with generating that dynamic SQL in a stored procedure. starting with SQL 2005 there are methods to deal with permissions. OK: 1) if the SQL statement is very complex. So. there is almost every day someone who asks a question that is answered with use dynamic SQL with a quick example to illustrate. but have experience from other languages such as C++. it is not uncommon to end up with a dozen or more look-up tables that all have an id. as it describes a unique entity. in this section I will explore some situations where you could use dynamic SQL. there is often a real business problem which has a completely different solution without dynamic SQL ± and a much better one. Nevertheless. you save some network traffic and you do encapsulation. (Or at least it should!) Of course. In a proper database design. 2) As we have seen. a name column and some auditing columns. this is a bad idea. and future requirements may make the tables more dissimilar. not a login on the remote server. And while many of these questions taken by the letter have no other answer than dynamic SQL. You could just as well send the dynamic SQL from the client. and their semblance should be regarded as mere chance. So. and found that what you are impersonating is a local user or login. On top of that. but ever so often the person answering forgets to tell about the implications on permissions or SQL injection. . There seems to be several reasons why people want to parameterise the table name.This begs the question: is davidson here a local user or a remote user at SQL2K? Books Online is not very clear about this. But they do describe different entities. but I did some quick experimenting. Parameterising the table name to achieve generic code and to increase maintainability seems like good programmer virtue. the old truth does not hold. we can make this procedure work with help of dynamic SQL. but also that in many cases that it is an outright bad idea.) Common Cases when to (Not) Use Dynamic SQL When you read the various newsgroups on SQL Server.

there are situations where partitioning makes sense.) SELECT * FROM sales + @yymm This is a variation of the previous case. Another important benefit of partitioned tables is that deleting a partition is a pure meta-data operation. You should not have one sales table per month. but refer you to Books Online. It is much better to write ten or twenty stored procedures. So if you want to do the above (save the fact that SELECT * should not be used in production code). Finally. despite different tables being used. All tables have the same columns. These partitions can be split up over different filegroups to spread out the load. And. not in Standard. and the name includes some partitioning component. But in such case you should do partitioning properly. let's make this very clear: this is a flawed table design. it is important to get a grip of what's being used. Not the least. and the month that appear in the table name. so that there actually is a considerable gain in maintainability to only have them in one place. 12 months old. The table may be huge (say over 10 GB in size). so even with one procedure per table you would still need a dynamic dispatcher. typically year and sometimes also month. each table has its set of statistics and presumptions that are by no means interchangeable. In the following. when it comes to building a query plan. but the code would be in one single include file. I will look at three approaches to deal with partitioning without using dynamic SQL. Table partitioning is only available in Enterprise and Developer Edition.Furthermore. In this case. You would still have one set of procedures per table. But you may be stuck with a legacy application where you cannot easily change the table design. or you want to be able age to out old data quickly. you definitely lose control. which means that if you want to throw away all orders that are more than. For this reason. to save some typing. where there is a suite of tables that actually do describe the same entity. because the user may want to specify a date range for a search. you are on the wrong path. as far as SQL Server is concerned. say. you could consider using a pre-processor like the one in C/C++. you can do this with the wink of an eye. You can divide a table in up to 999 partition according to a partition function. writing one stored procedure per table is not really feasible. When you start to pass table and column names as parameters. (If your SQL statements are complex. you should have one single sales table. I'm not going into further details. even if they are similar to each other. Partitioned Tables Partitioned tables were added in SQL 2005. Now. in a complex data model. should be the first column of the primary key in the united sales table. admittedly. . New tables are created as a new year/month begins.

because for queries that include the partitioning column in the WHERE clause. you can now say: SELECT .. where you cannot easily merge the umpteen sales tables into one. OrderDate. EmployeeID INTO Orders96 FROM Northwind.. this view is not terribly efficient. as the query will access all tables in the view. OrderDate.. EmployeeID INTO Orders98 FROM Northwind. and the data will end up in the right table. so you can insert data into it..Views and Partitioned Views If you have an old application..sales2006 UNION ALL SELECT year = '2005'. the view is not updateable. you could make it into what SQL Server knows as a partitioned view. col2. . Furthermore. a simple approach is to define a view like this: CREATE VIEW sales AS SELECT year = '2006'. Here is a quick example/demo on how to properly set up a partitioned view.sales2005 UNION ALL .. col1. FROM dbo. EmployeeID INTO Orders97 FROM Northwind. FROM dbo. it's easy to add new tables to the view or remove old tables as the data is aged out. OrderDate. col2.... CustomerID. But with a few more steps. These columns need a default (so that processes that insert directly into these tables are unaffected) and a CHECK constraint. Here is how it looks for Orders96: ALTER TABLE Orders96 ADD Year char(4) NOT NULL CONSTRAINT def96 DEFAULT '1996' ... FROM sales WHERE year = '2006' AND .Orders WHERE year(OrderDate) = 1996 ALTER TABLE Orders96 ALTER COLUMN OrderID int NOT NULL SELECT OrderID + 0 AS OrderID. SQL Server will only access the relevant table(s). because it would break other parts of the application. CustomerID.Orders WHERE year(OrderDate) = 1997 ALTER TABLE Orders97 ALTER COLUMN OrderID int NOT NULL SELECT OrderID + 0 AS OrderID. Also. col1. Instead of composing the table name dynamically.. . A true partitioned view can be very efficient. And such a view is updatable. CustomerID. Assume that as legacy of a poor design we have these three tables: SELECT OrderID + 0 AS OrderID. a feature added in SQL 2000 (and available in all editions of SQL Server). Unfortunately.Orders WHERE year(OrderDate) = 1998 ALTER TABLE Orders98 ALTER COLUMN OrderID int NOT NULL go ALTER TABLE Orders97 ADD CONSTRAINT pk97 PRIMARY KEY (OrderID) ALTER TABLE Orders96 ADD CONSTRAINT pk96 PRIMARY KEY (OrderID) ALTER TABLE Orders98 ADD CONSTRAINT pk98 PRIMARY KEY (OrderID) First step is to a add Year column to each table..

At least I got it to work. EmployeeID Orders Year = @year CustomerID = N'BERGS' SQL Server will at run-time only access the OrdersNN table that maps to @year. CustomerID. when I tested this. the start-up expression was not included for some reason I have not been able to understand. For instance you can run: INSERT Orders(Year. In this case you could add a UNIQUE constraint with the partitioning column + the real primary key.Orders97 UNION ALL SELECT * FROM dbo. 12000. you can create the view: CREATE VIEW Orders AS SELECT * FROM dbo. you should list the colunms explicitly. You now have a proper partitioned view that you can perform inserts and updates through. This means that SQL Server determines at run-time whether to access the table or not. (In fact. 2) And if you run a query like: SELECT FROM WHERE AND OrderID. This will not be a proper partitioned view.Orders96 UNION ALL SELECT * FROM dbo. '19970101'. 'BERGS'. If this happens frequently. it may seem that all three tables are accessed. You should verify that it works for your situation. but when you define your real view. you should probably set up a job for this. If you look at the query plan casually.) For your real-world case you may find it prohibitive to change the primary key. when I ran a quick test. and access only one of the base tables. There is a risk that columns could come in different order in the tables. When a new table is added with a new year. OrderID. OrderDate. OrderDate. OrderID) Again.Orders98 Note: I have here use SELECT * to save some space in the article. for instance by each month. I only got this result on SQL 2005 and SQL 2008. but with some luck SQL Server may still apply start-up expressions. and the view will not be updatable. Finally. this must be performed for all three tables. On SQL 2000. so we need to drop the current primary key and recreate it: ALTER TABLE Orders96 DROP CONSTRAINT pk96 ALTER TABLE Orders96 ADD CONSTRAINT pk96 PRIMARY KEY (Year. but if you check the Filter operators you will find something called STARTUP EXPR. I leave out . EmployeeID) VALUES ('1997'.CONSTRAINT check96 CHECK (Year = '1996') This column must be the first column in the primary key. the view needs to be redefined.

there is a risk that you will hit a roadblock with a partitioned view: SQL Server only permits 256 tables in a query. you need to implement INSTEAD OF triggers to support this.. Maybe it's because their tables look like this: . with all the data in it. can continue to do so. Here is a fairly simple workaround: UPDATE tbl SET col1 = CASE @colname WHEN 'col1' THEN @value ELSE col1 END. Then you drop the old tables. The above is actually legal in T-SQL.. UPDATE or DELETE operations. You first create that new table. Then again. col2. please look it up in Books Online. You can find the full rules for partitioned views under the topic for CREATE VIEW in Books Online. Henrik Staun Poulsen suggested an alternate solution that evades this restriction. col2 = CASE @colname WHEN 'col2' THEN @value ELSE col2 END. but it requires running a cursor over sysobjects to compose a CREATE VIEW statement that you then execute with sp_executesql or EXEC(). Obviously. If they perform INSERT. Good reading is also Stefan Delmarco's detailed article SQL Server 2000 Partitioned Views. It's a very powerful SQL feature. Compatibility Views If you have very many tables. but replace them with views: CREATE VIEW sales200612 AS SELECT col1. UPDATE tbl SET @colname = @value WHERE keycol = @keyval In this case people want to update a column which they select at run time. In this case dynamic SQL would call for the user to have UPDATE permissions on the table. you can easily write a program in the language of your choice to generate the views and triggers. something not to take lightly. If you don't know about the CASE expression. this solution requires you to produce a lot of code. That would be an example of good use of dynamic SQL. So there is all reason to avoid it. This was a concentrated introduction to partitioned views. but you don't have to write it by hand.example code. . col3 FROM sales WHERE yearmonth = '200612' Old functions that uses dynamic SQL or whatever they do. one would wonder why people want to do this. but what happens is simply that the variable @colname is assigned the value in @value for each affected row in the table.

. this is simple to do without any dynamic SQL on SQL 2005 and later: DECLARE @mycolalias sysname SELECT @mycolalias = 'This week''s alias' CREATE TABLE #temp (a int NOT NULL.CREATE TABLE products (prodid prodid_type NOT NULL. 17 EXEC tempdb. but you may be able to live with that. sales_1 money NULL.. sales_2 money NULL. b int NOT NULL) INSERT #temp(a. is that this should be handled client-side. This issue has been addressed in SQL 2005. as sp_rename thinks you need to be a member of the db_owner or db_ddladmin database roles. you first get the data into a temp table.. month tinyint NOT NULL. prodname name_type NOT NULL. even if this is only a temp table. month)) SELECT col AS @myname The request here is to determine the name for a column in a result set at run-time.. @mycolalias.. 'COLUMN' SELECT * FROM #temp That is. PRIMARY KEY (prodid)) It could make more sense to move these sales_n columns to a second table: CREATE TABLE product_sales (prodid prodid_type NOT NULL. This trick works on SQL 2000 too. . sales_12 money NULL.) You will get an informational message Caution: Changing any part of an object name could break scripts and stored procedures.sp_rename '#temp. In any case. sales money NOT NULL. PRIMARY KEY (prodid. the statement fails with Invalid column name 'b'. There is yet one thing to be aware of on SQL 2000: you cannot use sp_rename in a stored procedure that is to be run by plain users. so if the the SELECT is in the same batch. although not entirely without dynamic SQL: you need put the SELECT from the temp table in EXEC(): EXEC('SELECT * FROM #temp') This is because on SQL 2000.b'. this is kind of difficult. My gut reaction. b) SELECT 12. But if your client is a query window is Management Studio or similar. . (You need to qualify sp_rename with tempdb to have it to operate in that database. . and then you use sp_rename to rename the column along your needs. sp_rename apparently does not trigger a recompile.

. The best solution for this particular problem is to use synonyms. SELECT @dbname = quotename(dbname) FROM . FROM otherdb..tbl JOIN . because EXEC permits you to specify a variable that holds the name of the procedure to execute...dbo. There may still be cases you may find that dynamic SQL is the only feasible situation... There seems to be several reasons why people want to do this. That is. Yet a way to avoid dynamic SQL is to use stored procedures for all inter-database communication. FROM ' + @dbname + ' . The most obvious is: SELECT @dbname = quotename(dbname) FROM . you only have to update the synonyms. This is bad. ' EXEC sp_executesql @sql. SELECT @sql = ' SELECT .dbo.. @params. ... the solution is different. If you want to get result sets back from db2. what you absolutely not should do is to have code that says: SELECT . But.dbo.. and most of the tables are in the remote database you can also do: SELECT @sql = ' SELECT . If there is a need for a second set of databases. This can be done in two ways.localtbl . if you are in db1 and need to get data from db2.otherdbtbl ' + ' JOIN dbo.. This can be dynamic.some_sp' EXEC @ret = @sp @par1.othertbl ' + ' JOIN ' + quotename(db_name()) + '... because if someone asks for a second environment on the same server. you call a stored procedure in db2. look at my article How to Share Data between Stored Procedures for suggestions.. and there is no need to use dynamic SQL.SELECT * FROM @dbname + '.tbl' In this case the table is in another database which is somehow determined dynamically. ' SELECT @dbname = quotename(dbname) FROM .localtbl . SELECT @sp = @dbname + '. you have a lot of code to change.. FROM dbo..dbo..dbo. if the query is complex.tbl as just otherdbtbl..tbl You can then refer to otherdb.. .. and depending on your underlying reason..... added in SQL 2005: CREATE SYNONYM otherdbtbl FOR otherdb. Get Data from another Database If you for some reason have your application spread over two databases. @par2.

So they get the idea that they should put the procedures in a "master" database.. query plans and error messages may indirectly disclose information to users who are not authorised to see it. not the current database. In any case. demonstrated by this example: sp_MSforeachdb 'SELECT ''?''. Some people see a problem with the same stored procedures in fifty databases. Thus.. bugs can easily lead to that information is exposed to people who should not see it. The trick here is that when you specify a system stored procedure in three-part notation with the database name. What else can you do? Some people might suggest that you should collapse the databases into one. and for sysadmin tasks dynamic SQL is usually a fair game. so what you win is that you don't have to write the control loop yourself. I don't give you the details on how to do it and I strongly recommend that you don't go there. because neither caching nor permissions are issues. which also means that use of it is not supported by Microsoft and it could be changed or withdrawn from SQL Server without notice. As above. I would never accept such a solution as a potential customer. the dynamic SQL in this example runs in @dbname.sp_executesql' EXEC @sp_executesql @sql. you are better off skipping stored procedures altogether and do all access from client code instead. and employ a strict row-level security scheme. sp_MSforeachdb uses dynamic SQL internally. A "Master" Database The scenario here is that you have a suite of databases with identical schema. you can do that. So while I mention the possibility. . COUNT(*) FROM sysobjects' As you might guess. Do Something in Every Database This sounds to me like some sysadmin venture. Whereas queries only would return the data they should. this is entirely unsupported. In fact. I have not played with this for a long time. if you feel that this is the only alternative. Another wild approach is to use SQL Server's own master database and install the application procedures as system procedures. the procedure executes in the context of that database. row-level security cannot be implemented entirely waterproof in SQL Server. Yes. because your code will entirely littered with dynamic SQL. In such case there is only one place you need to specify the database: the connection string. and each customer can access his database (but of course no one else's). Besides. is that every database serves a different customer. Nevertheless there is an kind of alternative: sp_MSforeachdb. I should hasten to add that sp_MSforeachdb is not documented in Books Online. The typical reason they are different databases and not one.. @params. and believe that they face a maintenance nightmare. It will give you a much bigger maintenance problem. In a complex application. I make use of that you can specify the procedure name dynamically with EXEC. but I am told that it still works in SQL 2008. .SELECT @sp_executesql = @dbname + '. Personally.

In my article. and then are puzzled why the query above does not return any rows.2. Arrays and Lists in SQL Server. but it is an extremely poor solution.. a security-aware customer would not even accept to share the same instance of SQL Server. This also permits you to have some flexibility. I also present performance data for the various methods.. I would not accept to share database with other customers. Some customers may prefer to skip an upgrade. These two conditions are the same: col IN (@list) col = @list IN does not mean "parse whatever data there is at runtime as a comma-separated list".' SELECT @sp_executesql = quotename(@dbname) + '. for long lists.4'. IN has extremely poor performance ± in some tests I did. The correct method is to unpack the list into a table with a user-defined function or a stored procedure. This is a very common question on the newsgroups. we have already seen how to do this: SELECT @sql = 'CREATE VIEW .2. you can do this with dynamic SQL. SELECT * FROM tbl WHERE col IN (@list) It is fascinating how may people who put '1. The correct solution is to avoid USE altogether in this case. Even more importantly.4' in @list.3. Well. Most often people have problems with the USE command. (You may ask whether not synonyms could be used to implement the "master" database..3. (Dynamic SQL is at the bottom of .) Creating an Object in Another Database This question sometimes comes up. make use of that you can set the database context by calling sp_executesql with threepart notation.. It's a compile-time shortcut for col = @a OR col = @b OR . In fact. you will get a match. and Use dynamic SQL is a far too common answer. if there is a row where col has the value '1. You cannot pass the list as a parameter to sp_executesql. Other customers may be prepared to pay for extra functions that only they have access to. You need this anyway. I mentioned that as a customer. it took SQL Server 15 seconds to build the query plan for a list with 10000 elements. so you would have to use EXEC() and be open to SQL injection. but require his own instance. I have not been able to think of anything useful. but if you find out something. In fact.. On top of that.What then is the real solution? Install the stored procedures in each database and develop rollout routines for your SQL objects.sp_executesql' EXEC @sp_executesql @sql That is. Yes. please drop me a line. the day you want to update the table definitions. I describe a whole range of ways to do this. it permits you to easily scale out and move some databases to a second server.

but there are jump-start links in the beginning of the article. both with dynamic SQL and static SQL. This article exists in two versions. one for SQL 2008 and later. If you are doing this. [1998] = SUM(CASE Year(OrderDate) WHEN '1998' THEN 1 ELSE 0 END) FROM Orders O JOIN Employees E ON O. where you transform rows into columns. so Microsoft reverted on that change for a while. But this example lapses into Dynamic Search Conditions A not too uncommon case is that the users should be able to select data from a broad set of parameters. Rather than going into details here. depending on which version of SQL Server you are using.LastName.EmployeeID = E. but the only option for good performance is to use dynamic SQL. you have not completed the transition to use stored procedure and you are still assembling your SQL code in the client. I refer you to my article. [1997] = SUM(CASE Year(OrderDate) WHEN '1997' THEN 1 ELSE 0 END). The procedure search_orders in the section on SQL injection is a very simple example of this. Any programmer that tackles this realises that writing a static solution with a tailor-made query for each combination of input parameters is impossible. This changed in SQL 2008. Dynamic Crosstab Another common request is to make a dynamic crosstab query. say that you want to display the number of orders handled by each employee in Northwind with one column per year. This query works well: SELECT E. because the original implementation had a serious bug. it's simple to write a single static query with conditions like: AND (CustomerID = @custid OR @custid IS NULL) But in SQL 2005 and earlier if is not possible to get good performance from such a query. and one for earlier versions. SELECT * FROM tbl WHERE @condition If you are considering to write the procedure CREATE PROCEDURE search_sp @condition varchar(8000) AS SELECT * FROM tbl WHERE @condition Just forget it.EmployeeID GROUP BY E. Dynamic Search Conditions. However that is a bit complicated. It most cases. [1996] = SUM(CASE Year(OrderDate) WHEN '1996' THEN 1 ELSE 0 END). where I discuss this type of searches in more detail and where I present several methods. For instance.LastName . provided that you use the RECOMPILE hint.that list!) This is a long article.

The general technique is a two-step operation: 1) Get the unique values to pivot on. you will want to employ dynamic SQL for this. not to say impossible to make the procedure fool-proof since it accepts query text as parameter. in this example. As this article is already long enough. but leave it to you to explore it on your own. but I have heard several good comments about it. generate a query like the one above. The file for pivot_sp includes an example to demonstrate this. col2. it takes some time to get everything in place. I have never used it myself. Rather I recommend that you do DENY EXECUTE ON pivot_sp TO public To make sure that plain users cannot run it. SELECT * FROM tbl ORDER BY @col This can easily be handled without dynamic SQL in this way: SELECT col1. but you should not make a procedure like this one accessible to anyone.But in many situations you don't exactly which columns you will have in the data. This is no problem as long as you use it as your own utility procedure and have full control over the input. 2) with those values. While it's a short description. One approach is to set an upper limit of how many output columns you support and use dummy names for the columns. However. A SELECT statement returns a table. The procedure takes a number of parameters permitting you to specify the query. the rows to group by and to pivot by. you use the technique I described in the section SELECT col AS @myname. in the very most cases. or even how many there will be. and it is very difficult. and which aggregation operation you want.tbl ORDER BY CASE @col1 WHEN 'col1' THEN col1 WHEN 'col2' THEN col2 WHEN 'col3' THEN col3 END . For instance. we may not know beforehand for which years there are orders. If you make a call to pivot_sp in a stored procedure. col3 FROM dbo. which is a third-party tool. something I have adapted from a procedure originally written by SQL Server MVP Itzik Ben-Gan. so there is no way you can write a static SELECT statement to achieve this. I don't go into details to try to explain how it works. You can make a shortcut with the stored procedure pivot_sp. and a table has a known number of columns with known names. Once you have run the query. this call will succeed as ownership chaining applies. Another option for dynamic crosstab is RAC. it is wide-open to SQL injection. I like to stress one thing though: The way pivot_sp is written. And there is not really any alternative.

if you are not acquainted with it. since SQL 2005 added new syntax that permits a variable: SELECT TOP(@n) col1. CASE @col1 WHEN 'col3' THEN col3 ELSE NULL END If you also want to make it dynamic whether the order should be ascending or descending. review the CASE expression in Books Online. col2. add one more CASE: SELECT col1. the optimizer may avoid the sort if there is a suitable index. CASE @col1 WHEN 'col2' THEN col2 ELSE NULL END. If you add an ORDER BY clause in dynamic SQL. It should be added that these solutions has the disadvantage that they will always cause a sort which for a large data set could be expensive. Instead.Again. Note that if the columns have different data types you cannot lump them into the same CASE expression. SQL Server MVP Itzik Ben-Gan had a good article on this topic in the March 2001 issue of SQL Server Magazine.tbl ORDER BY CASE @col1 WHEN 'col1' THEN col1 ELSE NULL END. you can do this: SELECT col1. where he offers other suggestions. col2 FROM tbl . CASE @sortorder WHEN 'DESC' THEN CASE @col1 WHEN 'col1' THEN col1 WHEN 'col2' THEN col2 WHEN 'col3' THEN col3 END ELSE NULL END Or use the form in the second example to deal with different data types. SELECT TOP @n FROM tbl This is no longer an issue. col3 FROM dbo. col3 FROM dbo. col2. as the data type of a CASE expression is always one and the same.tbl ORDER BY CASE @sortorder WHEN 'ASC' THEN CASE @col1 WHEN 'col1' THEN col1 WHEN 'col2' THEN col2 WHEN 'col3' THEN col3 END ELSE NULL END ASC.

(But it's not worth to change the permissions only for this. Plan caching obviously has nothing to do with it. the set of tables and columns are supposed to be constant. A dynamic TOP is probably a better choice. it may be better to create one table that all clients can share. But there is an alternative: CREATE PROCEDURE get_first_n @n int AS SET ROWCOUNT @n SELECT au_id. If you want to create a permanent table which is unique to a user. as long as you can accept the security implications. CREATE TABLE @tbl The desire here is to create a table of which the name is determined at run-time. Nevertheless: Why? Why would you want to do this? If you are creating tables on the fly in your application. Sometimes when people are doing this. If a stored procedure has a static CREATE TABLE in it. but you don't want to stay connected and therefore cannot use temp tables. au_lname. so you need to use dynamic SQL to use TOP.On SQL 2000. as this is a built-in feature in SQL Server. TOP does not accept variables. If we just look at the arguments against using dynamic SQL in stored procedures. If you say: CREATE TABLE #nisse (a int NOT NULL) then the actual name behind the scenes will be something much longer. I discuss this method a little more closely in my article How to Share Data between Stored Procedures. few of them are really applicable here. CREATE TABLE with Unknown Columns . They may change with the installation of new versions. au_fname FROM authors ORDER BY au_id SET ROWCOUNT 0 It can be disputed whether SET ROWCOUNT @n is really a better solution than running a dynamic SQL statement with TOP. and no other connections will be able to see this instance of #nisse. so dynamic SQL will not change anything. you have missed some fundamentals about database design. In a relational database. SQL Server MVP Aaron Bertrand has an article which is the standard reference on this topic. the user who runs the procedure must have permissions to create tables. it appears that they want to construct unique names for temporary tables. Etc. This is completely unnecessary. but where the first column is a key which is private to the client.) I guess a common reason for wanting to do this is to implement paging in web applications. but not during run-time.

you should seriously consider to run your SQL from a client program. I can't really provide any alternatives. @srvproduct='Any'. Such a table is visible to all processes (so you may have to take precautions to make the name unique). determined in the flux of the moment. You can use sp_addlinkedserver to define the linked server at run-time. But the real question is: what are these guys up to? If you are working with a relational database. then there is something fundamentally wrong. one with two # in the name. and you don't know the structure of your data until run-time. There exists however an alternative. One solution is to create a global temp table.. VB or Perl. As I have never been able to fully understand what the underlying business requirements are. @provider='SQLOLEDB'. but in this case we want to access a linked server of which the name is determined at run-time. for instance ##temp. be that C#. because they don't know the structure of the table until run-time. and unless you explicitly drop it. Two of the solutions for dynamic database names apply here as well: y On SQL 2005 and later.some_sp' EXEC @ret = @sp @par1. dynamic SQL is probably the best way if you are on SQL 2000. although it's only usable in some situations. you can build the SP name dynamically: SET @sp = @server + 'db.sysdatabases go EXEC sp_dropserver MYSRV go CREATE PROCEDURE linksrv_demo @server sysname AS IF EXISTS (SELECT * FROM master. @datasrc=@@SERVERNAME go CREATE PROCEDURE linksrv_demo_inner WITH RECOMPILE AS SELECT * FROM MYSRV.Sometimes I see persons on the newsgroups that are unhappy.db. But I would suggest that if you need to go this road. @par2. because it disappeared when the dynamic SQL exited..remotetbl y y If you can confine the access to the linked server to a stored procedure call.master. the best solution is probably to use synonyms: CREATE SYNONYM myremotetbl FOR Server. and composing dynamic SQL strings is easier in languages with better string capabilities. because they create a temp table from dynamic SQL..sysservers WHERE srvname = 'MYSRV') EXEC sp_dropserver MYSRV . When told that they have to create the table outside the dynamic SQL. Because. Linked Servers This is similar to parameterising the database name. and then they can't access it. all access to that table would have to be through dynamic SQL. as demonstrated by this snippet: EXEC sp_addlinkedserver MYSRV.dbo.dbo.dbo. If you want to join a local table with a remote table on some remote server. they respond that they can't. it exists until your process exits.

In fact. it must also have the database and tables that you access. @datasrc=@server EXEC linksrv_demo_inner EXEC sp_dropserver MYSRV go EXEC linksrv_demo 'Server1' EXEC linksrv_demo 'Server2' There are two procedures. plain users do not apply.) As you can see in the example. As the linked server must exist when the procedure is created. @srvproduct='Any'. you may have to deal with up to three levels of nested quotes. which I subsequently drop once the procedure has been created. (This is because the optimizer builds a plan for the distributed query when the procedure is compiled. ' + '''SELECT * FROM Northwind.dbo. but as they say. to prevent that a cached plan does not access a different server.EXEC sp_addlinkedserver MYSRV. The above is only possible under certain conditions: y y The procedure must be run by someone who has privileges to set up linked servers. (It goes without saying. If you don't watch out. you cannot have several instances of the procedure running. I don't think this is really necessary. and then at runtime defines MYSRV to point to @server. you may not even have to split the code over two procedures. Their second argument is an SQL string. Since the remote SQL string can include string literals. that you should use the alias in this procedure only. Thus. I first create a dummy entry for MYSRV. This is a safety precaution. The function quotestring() that I showed you earlier can be of great help: .) linksrv_demo is the outside interface which takes a server name as a parameter. and they do no accept variables. normally only the roles sysadmin and setupadmin have these permissions. as SQL Server should sense the changed definition. Strict discipline is absolutely necessary when working with dynamic SQL for OPENQUERY. you can spend a full day looking at things like: DECLARE @sql varchar(8000) SELECT @sql = 'SELECT * FROM OPENQUERY(MYSRV. (Not only must the linked server exist. I've added WITH RECOMPILE to linksrv_demo_inner. linksrv_demo_inner is the procedure where we actually access the linked server.) So any single parameter you want to pass to the SQL statement for that remote server requires you to use dynamic SQL.Orders ' + 'WHERE CustomerID = N''''VINET'''''')' PRINT @sql EXEC(@sql) to try to find out if you might you have one ' too many or too few. better safe than sorry. @provider='SQLOLEDB'. Since you change a server-wide definition. OPENQUERY The rowset functions OPENQUERY and OPENROWSET often calls for dynamic SQL.

dbo. Dynamic SQL and Maintenance Tasks I've written this text with a main focus on application code. code that runs once a night or once a week or even less frequently. dynamic SQL is almost always a fair game..DECLARE @remotesql nvarchar(4000).authors WHERE state = ' + dbo. Here. and the GUI it is to be run from is Query Analyzer or SQL Server Management Studio (presumably because it is a sysadmin procedure). for this sort of code. two points about SQL injection I like to make. Typically you would use a temp table to hold the data. you can join OPENQUERY with local tables. . Generally. as the SQL statement easily can exceed the limit of 129 characters for the input parameter to quotename(). Rather than giving an example.quotestring(@remotesql) + ')' PRINT @localsql EXEC (@localsql) The built-in function quotename() is usually not useful here. so that only rows of interest are brought across the wire. bad usage of dynamic SQL can cause serious harm by opening for SQL injection. To make the output easy to digest. and result in code that is difficult to read and maintain. This you cannot do with EXEC(). Then again. because it is mainly in application tasks. I refer you to the source code for the popular (but undocumented) system procedure sp_who2. you want the column width to be so wide that no data is truncated. and is to be run by users with db_owner privileges. You can find the code by entering exec master. in which case there are no permission issues. Dynamic Column Widths Say that you write a stored procedure that is to present some data. @localsql nvarchar(4000). poor query-plan reuse. you can use EXEC() to run an SQL statement on a linked server.sp_helptext sp_who2. This is something you can achieve with dynamic SQL. there are no permissions issues. @state char(2) SELECT @state = 'CA' SELECT @remotesql = 'SELECT * FROM pubs. Query plans are rarely an issue. Since EXEC() at linked servers can take parameters. ' + dbo. but neither do you want any extraneous spaces. On SQL 2005 and later. The same applies to code that does not require permissions outside the database. And if the code is to be run by users with sysadmin privileges. this can make things considerably easier.quotestring(@state) SELECT @localsql = 'SELECT * FROM OPENQUERY(MYSRV. I like to briefly discuss code is for maintenance jobs. There are however.

1. If you are a DBA that writes some stored procedure to be run by junior operators that do not have sysadmin privilege themselves.se. 2009-02-14 .programming or comp. Karl Jones. 2009-09-12 ± Gennadi Gretchkosiy pointed out using that SELECT * in a partitioned view is not OK. Acknowledgements and Feedback I like to thank the following persons who have provided valuable suggestions and input for this article: SQL Server MVPs Tibor Karaszi. I encourage you to post to any of the newsgroups microsoft. since the bug mentioned in the entry from 2009-02-14 has been fixed. that Microsoft is now reverting on because of a serious bug. Henrik Staun Poulsen. Revision History 2011-06-23 ± Updated the text in the section on Dynamic Search Conditions to mention the RECOMPILE hint. A user could create a table with a name that injects an SQL command into your maintenance script when you run it. Not the least I like to thank all you people who have pointed out typos and spelling errors. you will get a mess.Removed text in the section on Dynamic Search Conditions that referred to the new behaviour of OPTION (RECOMPILE) in SQL 2008. as well as Pankul Verma. 2008-12-06 ± Modified the section on dynamic crosstab to stress that pivot_sp is open to SQL injection.sqlserver. Umachandar Jaychandran. Various other minor changes. language or formatting. Added a section on dynamic crosstab. Marcus Hansfeldt. Steve Kass. This is particularly important if there are non-sysadmin users that own databases. If you are the DBA at a hosting company. Jeremy Lubich and Simon Hayes. this is a risk that you definitely should not neglect.databases. I also like to thank Frank Kalis for providing the German translation. Hal Berenson and Aaron Bertrand. 2. Keith Kratochvil. Gennadi Gretchkosiy. Just keep those letters and cards coming! If you have suggestions for improvements or corrections on contents.public. please mail me at esquel@sommarskog. Anthony Faull. you must of course take precaution against SQL injection.ms-sqlserver. 2008-12-02 ± Updated the article for SQL 2008. be careful to use quotename() when you build the SQL strings. If you have technical questions that any knowledgeable person could answer. If you write a job that performs operations on tables in every database. so that they don't outsmart you. . Rewrote the section on Sales + @yymm tables and added one more approach. If the columns come in different order in the underlying tables.

I'm now giving a very quick example of partitioned views for the sales + @yymm case.2008-06-06 ± Added an example on how to deal with dynamic sort order in the section on ORDER BY. 2008-03-18 ± Added a section on how to handle a dynamic column alias. Back to my home page. resulting in lots of new text. Minor language corrections. 2006-07-25 ± Corrected syntax in example with cursor variable after comment from Anthony Faull. and I put more stress on SQL injection. 2004-02-08 ± German translation now available. lots of old text dropped. and I note that prefixing with dbo is essential for query-plan reuse.Net. I also stress the importance of using parameterised statements for query-plan reuse. 2006-04-23 ± Thoroughly reworked the article to cover SQL 2005 in full. 2006-12-27 ± In the section Caching Query Plans. and many sections rearranged. 2003-12-02 ± Added example of using cursor variable with dynamic SQL. 2005-04-17 ± Added example of EXEC + sp_executesql with OUTPUT parameter. I'm now more strongly favouring sp_executesql over EXEC(). Modified description of first parameter to sp_executesql. The examples of cases where (not) to use dynamic SQL have had an overhaul as well. added a note on forced parameterisation and a demo of the performance penalty for failing to use parameterised queries. Added use of nvarchar(max) on SQL 2005 for quotestring and elsewhere. if not equally drastic. The article now also includes snippets for parameterised commands from VB6 and VB . .

Sign up to vote on this title
UsefulNot useful