Click here to Skip to main content
15,902,634 members
Articles / Programming Languages / SQL

Create and Execute Dynamic SQL on T-SQL

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
28 Nov 2011CPOL 17.1K   2   1
How to create and execute dynamic SQL on T-SQL.

Have you ever had the need to use dynamic SQL? Chances are that you had the need to manipulate a string to conform a SQL statement and then execute it via a SQLCommand -> CommandType.Text. This is a common technique in the .NET world, but how about using dynamic SQL on a Stored Procedure?

At times, I had the need to bring data from a table column and then use it to conform a SQL statement that will then be executed on demand. For example:

Imagine you have a table named t_settings, with a field named target_db. In this field, we store a database name. Now, using the data on this field, you could do something like:

SQL
declare @sql varchar(255)
select @sql = 'select * from ' + rtrim(target_db) + 
              '..another_table where 1=1' from t_settings
execute (@sql)

The execute statement provides all the magic. It allows you to execute a string command just as you would do with a SP.

Below is a somewhat silly example that you can try if you have the AdventureWorks database available.

SQL
declare @ContactID varchar(3)
declare @Sql varchar(255)
select @ContactID = Cast(ContactID as varchar) from 
        person.contact where EmailAddress = 'kim3@adventure-works.com'
select @ContactID
--Manipulate the String that will become the query that we need to execute.
select @Sql = 'Select * from Sales.SalesOrderHeader where contactid = ' + @ContactID
execute (@sql)

Happy coding, Will.

This article was originally posted at http://feeds.feedburner.com/blogspot/NyVKAz

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSQL Injection Alert Pin
RichYards6-Dec-11 13:20
RichYards6-Dec-11 13:20 
Sometimes dynamic SQL cannot be avoided. However, be VERY Careful. SQL injection attacks can occur even if you are not using user entered values directly. It could be laying in wait in the database for an unwary database engineer to carelessly use it in a dynamic execute call. Consider:


SQL
CREATE TABLE Users (UserName varchar(32), Email varchar(32))

INSERT INTO Users VALUES ('User1', 'user1@email.com')
INSERT INTO Users VALUES ('User2', 'user2@email.com')
INSERT INTO Users VALUES ('''; drop table users--', 'hahaha@email.com')


Now if you were to want to use dynamic SQL to change an email address you might be tempted to use:

SQL
DECLARE @Username VARCHAR(32)
DECLARE @SQL varchar(1028)

SELECT TOP 1 @Username = UserName FROM Users WHERE Email = 'hahaha@email.com'

SET @SQL = 'update users set email = ''newemail@email.com'' where username = ''' + @Username + ''''

EXECUTE (@SQL)

SELECT * FROM Users
PRINT @SQL -- oops!


An better approach would be to use the sp_executesql stored procedure. It is a little more cumbersome to set up, but it give you a parameterized query. The above dynamic update could be written as:

SQL
DECLARE @Username VARCHAR(32)
DECLARE @SQL nvarchar(1028)

SELECT TOP 1 @Username = UserName FROM Users WHERE Email = 'hahaha@email.com'

SET @SQL = N'update users set email = ''newemail@email.com'' where username = @Username'

EXECUTE sp_ExecuteSQL @SQL, N'@Username varchar(32)', @Username

SELECT * FROM Users

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.