Lesson 43. Dynamic SQL

Dynamic SQL is another one of those things that I am going to aggressively suggest you do not use for reasons.

Dynamic SQL allows you to build a SQL statement into a string which then can be executed. You will find this useful when you are executing SQL from within your Python scripts. It is less useful in pure stored procedures.

But, like usual, I am going to tell you about them now, because I talk about them in the solutions section.

Examples

Selecting Data From A Table That Is Only Known At Run Time

In [ ]:

USE AdventureWorks2016

DECLARE @SQL NVARCHAR(255)
DECLARE @TableName NVARCHAR(255)

SET @TableName = 'Sales.SalesOrderDetail'

SET @SQL = 'SELECT * FROM ' + @TableName

EXEC sp_executesql @SQL

Last updated