Last Thursday I spoke at NTSSUG (North Texas SQL Server User Group). This is my local group (only 1.5 hours away from me) and my second time speaking for them. I don’t speak frequently so I’m always more than a bit nervous, but the crowd was great, laughed in the right spots, asked some really good questions and all around had some great energy. This post is primarily to share the Powerpoint and scripts I used during my demo but since I don’t like doing a post that is just links to some files I’m adding some of the content below as well.
Demystifying and Diminishing Dynamic SQL Difficulties PPT and Scripts
One of the ideas that I mentioned is that there are two types of Dynamic SQL as I see it. The processes that I use to create each are pretty similar but of course not quite the same.
One to Many
Using a single piece of code (typically a query) to generate multiple lines of SQL.
Example
SELECT 'ALTER DATABASE ' + QUOTENAME(name) + 'SET COMPATIBILITY_LEVEL = 130' FROM sys.databases WHERE compatibility_level < 130
Process
- Write the SQL statement first.
- Write the query that pulls the result set you want.
- Add the command to the query and convert it into to a string.
- Convert any literals that need to become dynamic into fields.
- Double any quotes
- Replace anything you want to make dynamic with ‘++’ then plug in the column/formula.
- Include schema names
- QUOTENAME is your friend.
- Copy the results to a query window.
- Test
- Parse
- Run a SINGLE command, preferrably in a transaction to test for correctness.
- Run the rest of the commands in a transaction if possible.
- After each failed test make one (or sometimes two) corrections and test again.
Many to One
Multiple lines of code are used to construct a single piece of SQL.
Example
DECLARE @SQL nvarchar(500); DECLARE @SchemaName nvarchar(50) = 'sys'; DECLARE @TableName nvarchar(50) = 'databases'; SET @SQL = N'SELECT * FROM ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName); --EXEC sp_executesql @SQL; PRINT @SQL; GO
Process
- Write the SQL statement first.
- Declare a variable to store the code, and convert the code into a string.
- Convert any literals that need to become dynamic into fields.
- Double any quotes
- Declare any variables that are going to need
- Replace anything you want to make dynamic with ‘++’ then plug in the column/formula/variable.
- Include schema names
- QUOTENAME is your friend.
- Copy the results to a query window.
- Test
- Parse
- Run a SINGLE command, preferrably in a transaction to test for correctness.
- Run the rest of the commands in a transaction if possible.
- After each failed test make one (or sometimes two) corrections and test again.