Execute Dynamic SQL commands in SQL Server http://www.mssqltips.com/tip.asp?
tip=1160
join the community
Home Tips Tools Tutorials Webcasts Whitepapers Questions Subscribe:
Learn more about SQL Server
Execute Dynamic SQL commands in SQL Server
By: Greg Robidoux | Comments (3) | Print | Share 1
More SQL Server Tools
Expand your SQL Server horizons with a Kindle loaded with 5 eBooks
SQL Sentry Performance Advisor® for SQL Server
< Prev - | 1 | 2 | 3 | 4 | - Next > SQL Refactor
SQL comparison toolset
Problem SQL diagnostic manager
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 Virtual Restore
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
SQL Server Tips
Latest
Active Comments
Related
Latest
2. Using EXEC
SQL Server script to rebuild all indexes for
With this approach you are building the SQL statement on the fly and can pretty much do whatever you need to in all tables and all databases
order to construct the statement. Let's say we want to be able to pass in the column list along with the city.
Locking Down PII Data in SQL Server - Part
For this example we want to get columns CustomerID, ContactName and City where City = 'London'. 2
As you can see from this example handling the @city value is not at straight forward, because you also need to define Restoring a SQL Server database that uses
the extra quotes in order to pass a character value into the query. These extra quotes could also be done within the Change Data Capture
statement, but either way you need to specify the extra single quotes in order for the query to be built correctly and
therefore run. Identifying PII Data to Lock Down in SQL
Server - Part 1
DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75) Remove HTML tags from strings using the
DECLARE @city varchar(75) SQL Server CLR
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London''' Getting started with Code Snippets feature
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
of SQL Server Denali
EXEC (@sqlCommand)
SQL Server Stored Procedure Tutorial
SQL Server Central Management Server
Security
Moving database files for a replicated SQL
Server database
Maintain SQL Server Replication using
3. sp_exectesql Source Control
With this approach you have the ability to still dynamically build the query, but you are also able to still use Active Comments
parameters as you could in example 1. This saves the need to have to deal with the extra quotes to get the query to
Index Fragmentation Report in SQL Server
build correctly. In addition, with using this approach you can ensure that the data values being passed into the query
are the correct datatypes. 2005 and 2008 (4)
DECLARE @sqlCommand nvarchar(1000) Restoring a SQL Server database that uses
DECLARE @columnList varchar(75) Change Data Capture (2)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City' Locking Down PII Data in SQL Server - Part
SET @city = 'London' 2 (1)
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city Performance Advantages of SQL Server
Filtered Statistics (2)
Collecting SQL Server performance counter
data for trending (2)
SQL Server script to rebuild all indexes for
all tables and all databases (17)
1 de 3 28/06/2011 10:02 p.m.
Execute Dynamic SQL commands in SQL Server http://www.mssqltips.com/tip.asp?tip=1160
Getting started with Code Snippets feature
of SQL Server Denali (0)
SQL Server 2005 Database Mail Install
Hangs (1)
Introduction to Utility Control Points in SQL
Server 2008 R2 (1)
So here are three different ways of writing dynamic queries. In addition to the above, here are some other articles SQL Server snapshot replication fails when
that give you other perspectives on setting up and using dynamic SQL. trying to import data from the distributor
(2)
The Curse and Blessings of Dynamic SQL
Introduction to Dynamic SQL (Part 1) Related
Introduction to Dynamic SQL (Part 2)
Dynamic SQL execution on remote SQL
Next Steps Server using EXEC AT
If at all possible look at avoiding the use of dynamic SQL especially where you start to manipulate the overall Run a Dynamic Query against SQL Server
query string. This could potentially open up other areas of concern such as SQL Injection and performance without Dynamic SQL
issues.
Look into using dynamic SQL in your stored procedures by employing one of the three techniques above instead Recover from a SQL Injection Attack on SQL
having the code generated from your front end application. Server
Using the CASE expression instead of
Last Update: 1/19/2007 dynamic SQL in SQL Server
< Prev - | 1 | 2 | 3 | 4 | - Next >
Execute Dynamic SQL commands in SQL
Server
Sponsor Information
Try the free performance monitoring tool from Idera!
SQL Backup Pro was the smartest kid at school. Head of the class for compression, encryption and centralized
management. Discover why.
SQL Server Issues? Not sure where to turn for answers? Innovative SQL DBA consultants
Make the most of MSSQLTips...Sign-up for the newsletter
Valuable SQL Server web casts on Performance Tuning, Development, Administration, Disaster Recovery,
Replication and more...
Community Questions
Latest
Active Questions
Latest
extended property
SQL 2005
replication in sql server
replication in sql server
SQL Server process stuck in killed\rollback
state (SQL SERVER 2008)
Develop the Report or query for listing the
database name which does not have
database extendend property
SSRS 2008 Data Driven Subscriptions to
SSAS cube for retrieving Roles membership
data
Tables names are not being diskpalyed in
Index Fragmentation list
SQL express 2005 installed on Windows 7
OS having live IP not getting connected to
2 de 3 28/06/2011 10:02 p.m.
Execute Dynamic SQL commands in SQL Server http://www.mssqltips.com/tip.asp?tip=1160
desktop application when tried connect
why we do monitoring in sql server and
what is the benefit of monitoring in sql
server
Active Questions
replication in sql server (1)
SQL Server process stuck in killed\rollback
state (SQL SERVER 2008) (1)
SSRS 2008 Data Driven Subscriptions to
SSAS cube for retrieving Roles membership
data (1)
SQL express 2005 installed on Windows 7
OS having live IP not getting connected to
desktop application when tried connect (1)
Tables names are not being diskpalyed in
Index Fragmentation list (1)
SQL 2008 Cube Structure Diagram just like
in SQL 2000 (1)
Filtering, Sorting, Drilling in SSRS 2005
Reports (1)
SQL cluster installation (3)
Report Builder 3.0 charts (1)
Deploy Sql Server Analysis Services Cube in
FrontEnd (1)
Announcements
Events
Giveaways
Contribute
Events
Free Live Webcast
TempDB: Performance and Manageability
(July 13th)
Giveaways
Giveaways
Win a Kindle with SQL Server eBooks
MSSQLTips is giving away a Kindle with SQL
Server eBooks.
The winner will be selected on July 20,
2011.
Contribute
Contribute and make some money!
Become a MSSQLTips author
Share your knowledge about SQL server
with the MSSQLTips community. Just about
every day you probably learn something
new, so share that knowledge.
Copyright (c) 2006-2011 Edgewood Solutions, LLC All rights reserved
privacy | disclaimer | copyright | advertise | contribute | feedback | giveaways | user groups | about
Some names and products listed are the registered trademarks of their respective owners.
CareerQandA.com | MSSharePointTips.com | MSSQLTips.com
3 de 3 28/06/2011 10:02 p.m.