0% found this document useful (0 votes)
13 views

Dynamic SQL

Uploaded by

zenandecewuka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Dynamic SQL

Uploaded by

zenandecewuka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

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.

The example uses a simple select statement:

--declare a varchar or nvarchar variable of suitable length to stire your query


declare @sql nvarchar(100)

--set your variable equal to any valid SQL statement


--in this example we have a simple select statement
set @sql = 'select *
from StudentDetails'

--execute the statement using the exec (note the brackets)


exec (@sql)

--Alternatively execute using the system stored procedure


EXECUTE sp_executesql @sql

You can also build an SQL string using variables and parameters:

create proc SelectStudent


@StudentNumber varchar(10)
as
begin

--declare a varchar or nvarchar variable of suitable length to stire your query


declare @sql nvarchar(100)

--set your variable equal to any valid SQL statement


--in this example we have a simple select statement
--with a where clause
--Make sure when passing varchar parameters that you have your enclosing quotes

set @sql = 'select * ' +


'from StudentDetails ' + --note the space after the table
name to ensure the final SQL is well formatted
'where StudentNumber = ' + @StudentNumber
/*
For example, this statement could resolve to SQL
select *
from StudentDetails
where StudentNumber = 1234567890

this statement will execute but will cause an implicit cast


*/

set @sql = 'select * ' +


'from StudentDetails ' + --note the space after the table
name to ensure the final SQL is well formatted
'where StudentNumber = ''' + @StudentNumber + ''''

--note the difference from the previous statement,


--this one includes enclosing quotes for the parameter

1|Page
/*
For example, this statement could resolve to SQL
select *
from StudentDetails
where StudentNumber = '1234567890'

this statement will execute without causing an implicit cast


*/

--execute the statement using the exec (note the brackets)


exec (@sql)
end

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.

DECLARE @sqlCommand nvarchar(1000)


DECLARE @columnList varchar(75)
DECLARE @city varchar(75)

SET @columnList = 'CustomerID, ContactName, City' --this would be sent


through as a parameter to a stored procedure

SET @city = 'London' -- this would also be a parameter

SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'

EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @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.

create proc CreateInvestor


@InvestorId int,
@InvestorName varchar(50),
@InvestorSurname varchar(50),
@PortfolioList varchar(30)
as

3|Page
begin

declare @PortfolioId int,


@SQL nvarchar(1000)

begin transaction

insert into Investor values(@InvestorId, @InvestorName, @InvestorSurname)

if @@Error <> 0
begin
rollback transaction
return
end

set @SQl = 'insert into Investor_Portfolio_options ' +


'select ' + cast (@InvestorId as varchar(10)) + ',' +
'PortfolioOPtionId ' +
'from Portfolio_Options ' +
'where POrtfolioOPtionId in (' + @PortfolioList + ')'

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

You might also like