Tip of the day : Execute Dynamic SQL commands in SQL Server - DOTNET

Tip of the day : Execute Dynamic SQL commands in SQL Server

SQL Server offers two ways of running a dynamically built SQL statement. 

1.Using EXEC
2.Using sp_executesql

1. Using EXEC
With this approach you are building the SQL statement on the fly and can pretty much do whatever you need to in order to construct the statement. 

For this example we want to get columns CustomerID, ContactName and City where City = 'London'.

/* T-SQL Statement
============================= */

DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)

/* ============================= */


2. sp_exectesql
With this approach you have the ability to still dynamically build the query, but you are also able to still use parameters. This saves the need to have to deal with the extra quotes to get the query to build correctly.  In addition, with using this approach you can ensure that the data values being passed into the query are the correct datatypes.

/* T-SQL Statement
============================= */

DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = 'London'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city


/* ============================= */
Copyright © 2015 DOTNET All Right Reserved