Dynamic SQL
Dynamic SQL
Contents
Executing SQL .......................................................................................................................................... 1
Dynamic SQL ........................................................................................................................................... 2
Advanced Example .............................................................................................................................. 3
References .............................................................................................................................................. 4
Executing SQL
We are used to writing SQL and executing it inside the query window or as a stored procedure. However, you
can also execute an SQL statement using exec or the sp_executesql system stored procedure.
An SQL variable must be declared as a varchar or nvarchar. You then set your variable equal to any valid SQL
statement (from a simple select all the way through to a complex nested join). Make sure your variable is long
enough to hold the final string – rather make it too big than too small and have a part of your built SQL cut off.
You can also build an SQL string using variables and parameters:
1|Page
/*
For example, this statement could resolve to SQL
select *
from StudentDetails
where StudentNumber = '1234567890'
In order to check that your SQL string is syntactically correct, you can print the string before executing it:
print @sql
This will output the string in the messages tab of the query window:
Of course the examples given above can both be completed without the use of an SQL variable and should
preferably not use an SQL variable. However, in some instances it is useful to be able to execute queries which
are not known beforehand and are not fixed. Under these circumstances we build an SQL query string “on-the-
fly” or dynamically, hence referring to dynamic SQL.
Dynamic SQL
For example, suppose you would like your users to be able to select the fields which must be included in the
result set. In cases such as these you can build an SQL string and execute the resultant SQL.
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
As can be seen the resulting string in @sqlCommand is a valid SQL statement which is then built dynamically
based on the values of the parameters and then executed.
2|Page
Advanced Example
INVESTOR
PK InvestorId
InvestorName
InvestorSurname
INVESTOR_PORTFOLIO_OPTIONS
PK InvestorId
PK PortfolioOptionId
PORTFOLIO_OPTIONS
PK PortfolioOptionId
PortfolioOptionName
When a new client signs on as an investor, their details must be entered in to the database, together with the
investment portfolio options they have selected. Write a full stored procedure which will allow the required
changes to be made to the database. You should make sure that data integrity and database consistency will be
maintained. Assume that the InvestorId is assigned by the client application. The portfolio options are sent
through from the client application in the format <portfolioOptionId1>, <portfolioOptionId3>,
<portfolioOptionId7>.
The PortfolioString could contain any number of PortfolioIDs, the number of selected options is not known
beforehand. Therefore all of the following strings are valid:
1,5,17,24
2,6,9
8
5,9,26
23,27
Dynamic SQL will work well in this instance as it will allow you to insert all the selected portfolio options in
Investor_Portfolio_Options in a single statement.
3|Page
begin
begin transaction
if @@Error <> 0
begin
rollback transaction
return
end
exec(@sql)
if @@Error <> 0
begin
rollback transaction
return
end
commit transaction
end
Take care to make sure your SQL string is valid syntactically (for example make sure there are spaces after
string concatenation and that all brackets are correct) and semantically.
References
1. MSDN Library
4|Page