2. Ian Meade
• Working with databases and applications for
20 years.
• Working with SQL Server since 2001
• Certifications: MCM for SQL
2008, MCITP, MCSD.NET
3. What is dynamic SQL
• Dynamic doesn’t mean exciting or
interesting, it simply means that the SQL
queries are created at run time.
• There are two main use cases for dynamic
SQL.
– DBAs to automate maintenance activates.
– Used for complex and unpredictable queries
4. Why use dynamic SQL?
• Can lead to incredible performance and
scalability increases.
– Reductions in query execution time, memory
used, IO required
– Lead to reductions in locking / blocking, flushing
memory buffers and contention with other parts
of work load.
• Necessary as data sets grow to medium and
larger sizes.
5. BUT….
• Dynamic SQL will not improve every type of
query
• Issues around:
– more difficult to write and test and to change over
time
– security concerns that need to be resolved
– memory issues
– does not always fit easily into development
frameworks like ORM tools
6. Scary?
• Sounds like something to avoid?
• Yes – you should avoid dynamic SQL where
possible
– Only use it where it can help.
– Be careful with coding, testing and security.
7. Alternatives..
• Live with the problem
– Suitable for smaller datasets and possibly batch
operations
• Hard code the query
– Example
• Push functionality down to the client
• Hardcode parts of the query
8. Which queries to make dynamic
• Customer search is a good example.
• In most DBs, it usually has:
– Large number of rows
– Wide tables
– Composed of several tables joined together
– Unpredictable and complex search criteria
• Could be other parts of the DB.
– People / employees, Products other domain
specific entities
9. Implementing dynamic SQL
• Break query into parts
• Assemble the required parts
• Execute
– Use sp_executesql to parameterise query
• Security concerns
• Example
10. Extending 1…
• Make the search a re-usable function
• Allows:
– Re-use of search screen
– Auditing by recording search results
– Recording “as of” result sets
– Extending search rules – eg security.
• Example
11. Extending 2…
• Making search meta-data driven
• Re-using complex SQL “framework”
• Suitable for applications with many similar
search screens.
• Example