Click here to Skip to main content
15,895,142 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 

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.