solving sql server problems for millions of dbas and developers since 2006



SQL Server DBA Tips SQL Server Developer Tips SQL Server Business Intelligence Tips SQL Server Career Tips SQL Server Tip Categories SQL Server Tutorials SQL Server Webcasts SQL Server Whitepapers SQL Server Tools SQL Server Questions and Answers MSSQLTips Authors About MSSQLTips SQL Server User Groups MSSLQTips Giveaways MSSQLTips Advertising Options

MSSQLTips Facebook Page MSSQLTips LinkedIn Page MSSQLTips RSS Feed MSSQLTips Twitter Page MSSQLTips Google+ Page








Execute Dynamic SQL commands in SQL Server

By: | Read Comments (4) | Print

Greg is the President of Edgewood Solutions and a co-founder of MSSQLTips.com.

Related Tips: 1 | 2 | 3 | 4 | More

Problem
In some applications having hard coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamically create a SQL statement on the fly and then run that command.  This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET, ColdFusion or any other programming language.  But how do you do this from within a SQL Server stored procedure?

Solution
SQL Server offers a few ways of running a dynamically built SQL statement.  These ways are:

  1. Writing a query with parameters
  2. Using EXEC
  3. Using sp_executesql

1. Writing a query with parameters

This first approach is pretty straight forward if you only need to pass parameters into your WHERE clause of your SQL statement.  Let's say we need to find all records from the customers table where City = 'London'.  This can be done easily such as the following example shows.

DECLARE @city varchar(75)
SET @city = 'London'
SELECT * FROM customers WHERE City = @city

2. Using EXEC

With this approach you are building the SQL statement on the fly and can pretty much do whatever you need to in order to construct the statement.  Let's say we want to be able to pass in the column list along with the city. 

For this example we want to get columns CustomerID, ContactName and City where City = 'London'.

As you can see from this example handling the @city value is not at straight forward, because you also need to define the extra quotes in order to pass a character value into the query.  These extra quotes could also be done within the statement, but either way you need to specify the extra single quotes in order for the query to be built correctly and therefore run.

DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)

3. sp_exectesql

With this approach you have the ability to still dynamically build the query, but you are also able to still use parameters as you could in example 1. This saves the need to have to deal with the extra quotes to get the query to build correctly.  In addition, with using this approach you can ensure that the data values being passed into the query are the correct datatypes.

DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = 'London'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

So here are three different ways of writing dynamic queries.  In addition to the above, here are some other articles that give you other perspectives on setting up and using dynamic SQL.

Next Steps

  • If at all possible look at avoiding the use of dynamic SQL especially where you start to manipulate the overall query string.  This could potentially open up other areas of concern such as SQL Injection and performance issues.
  • Look into using dynamic SQL in your stored procedures by employing one of the three techniques above instead having the code generated from your front end application.


Related Tips: 1 | 2 | 3 | 4 | More | Become a paid author


Last Update: 1/19/2007

Share: Share 






Comments and Feedback:

Sunday, April 20, 2008 - 12:24:52 AM - Mazharuddin Read The Tip
Hi,I just discovered another benefit of using sp_executesql to execute the dynamic SQL.The Exec fails to work in case if the  SQL statement is lengthy (it obviously has a limitation of length)The same SQL statement works with Exec sp_executesqlBest regards,

Mazharuddin


Friday, May 09, 2008 - 2:47:59 PM - admin Read The Tip

Mazharuddin,

Thank you for the contribution.

Thank you,
The MSSQLTips.com Team


Wednesday, November 17, 2010 - 5:44:45 AM - Harsha Read The Tip

Hi,

I have a question regarding dynamic sql.

 

What would be difference between the 2 query

 

declare @script nvarchar(1000),
             @companyid int,
             @area tinyint

select comapnyid = 1 , @area = 1


select @script = 'select contactname , address, etc'+
                    + 'from tbljcontactstable' + convert(varchar(4) , @companyid)
                    + 'WHERE contact_area = ' +convert(varchar(4) , @area)

 


exec(@script)

AND

declare @script nvarchar(1000),
             @companyid int,
             @area tinyint

select comapnyid = 1 , @area = 1


SELECT @script = ''
SELECT @script = @script + 'select contactname , address, etc'
select @script = @script +  'from tbljcontactstable<comapnyid>'
select @script = @script +  'WHERE contact_area = <area>'
SELECT @script = REPLACE(@script, '<comapnyid>' , @companyid)
SELECT @script = REPLACE(@script, '<area>', @area)

exec(@script)

 


Friday, February 17, 2012 - 5:30:12 PM - Miguel Pena Read The Tip
I'm trying to get a SQL formula result: DECLARE @Amount DECIMAL(12,2) DECLARE @Formula NVARCHAR(100) DECLARE @Result DECIMAL(12,2) SET @Amount = 1000 SET @Fomula = N'ROUND(@Amount/1.16,2)' EXEC @Result = sp_executesql @Formula but when i execute it i receive the followin error: Msg 137, Level 15, State 1, Line 6 Must declare the scalar variable "@Fomula". Help me Please, mp


Post a Comment or Question

Keep it clean and stay on the subject or we may delete your comment.
Your email address is not published. Required fields are marked with an asterisk (*)

*Name   *Email   Notify for updates
Comments
*Enter Code refresh code


 
Sponsor Information
"Amazing, Amazing, Amazing! SQL doctor is truly one of the most powerful tools I have seen."

SQL Monitor, server monitoring so easy, your boss could do it. Try it online.

Need SQL Server help and not sure where to turn? Reach out to the Edgewood experts for a Health Check starting at $995.

Find and Fix SQL issues with Foglight Performance Analysis. Get a free copy.

Join the over million SQL Server Professionals who get their issues resolved daily.

Valuable SQL Server web casts on Performance Tuning, Development, Administration, SSIS and more...


Copyright (c) 2006-2012 Edgewood Solutions, LLC All rights reserved
privacy | disclaimer | copyright | advertise | about
authors | contribute | feedback | giveaways | user groups
Some names and products listed are the registered trademarks of their respective owners.


Edgewood Solutions LLC | MSSharePointTips.com | MSSQLTips.com