Optimizing Stored Procedure Performance: Kimberly L. Tripp Solid Quality Learning
Optimizing Stored Procedure Performance: Kimberly L. Tripp Solid Quality Learning
Optimizing Stored Procedure Performance: Kimberly L. Tripp Solid Quality Learning
Introduction
Kimberly L. Tripp, SQL Server MVP Principal Mentor, Solid Quality Learning
* In-depth, high quality training around the world! www.SolidQualityLearning.com
Consultant/Trainer/Speaker Coauthor for MSPress title: SQL Server 2000 High Availability Presenter/Technical Manager for SQL Server 2000 High Availability Overview DVD Very approachable. Please ask me questions!
Overview
Initial Processing - Review
Resolution Compilation/Optimization Execution/Recompilation
Recompilation Issues
When do you want to Recompile? Options for Recompilation? What to Recompile? Stored Procedure Best Practices
Naming Conventions Writing Solid Code Excessive Recompilations How? Detecting?
Resolution*
Execution
(first time or recompile)
Optimization
Compilation
Resolution
When a stored procedure is created all objects referenced are resolved (checked to see whether or not they exist). The create will succeed even if the objects do not exist
Procedures called that do not exist generate error
Cannot add rows to sysdepends for the current stored procedure because it depends on the missing object 'missingobjectname'. The stored procedure will still be created. Benefit: Recursion is allowed!
Tables, Views, Functions called that do not exist - do NOT generate error (unless in 6.5 compatibility mode)
Compilation/Optimization
Based on parameters supplied Future executions will reuse the plan Complete optimization of all code passed (more on this coming upmodular code!) Poor coding practices can cause excessive locking/blocking Excessive recompilations can cause poor performance
Execution/Recompilation
Upon Execution if a plan is not already in cache then a new plan is compiled and placed into cache What can cause a plan to become invalidated and/or fall out of cache:
Server restart Plan is aged out due to low use DBCC FREEPROCCACHE (sometime desired to force it)
Recompilation Issues
RECOMPILATION = OPTIMIZATION OPTIMIZATION = RECOMPILATION When do you want to recompile? What options do you have Recompilation? How do you know you need to recompile? Do you want to recompile the entire procedure or only part of it? Can you test it?
When to recompile?
When the plan for a given statement within a procedure is not consistent in execution plan due to parameter and/or data changes Cost of recompilation might be significantly less than the execution cost of a bad plan! Why? Faster Execution with a better plan Saving plans for reuse is NOT always beneficial Some plans should NEVER be saved
sp_recompile objname
Forces all plans with regard to that object to be invalidated (note: this does not force recompilation on views even though a view name is supported)
Statement Recompilation
Dynamic String Execution or Modularized Code
Do the execution plans match? Are they consistent? Yes then create the procedure normally No Determine what should be recompiled
Statement(s) Recompilation
Limited number of statements cause excessive recompilation
Dynamic String Execution Modular Code
Statement Recompilation
What if only a small number of statements need to be recompiled? The SQL Statement is not likely safe (i.e. it will not be saved and parameterized) Dynamic String Execution! Amazingly Flexible Permission Requirements Potentially Dangerous Advanced Examples
Complex large strings Changing database context Output parameters
Solution?
Scenario 1 upon first execution Parameters are passed such that the ELSE condition executes BOTH Block1 and Block2 are optimized with the input parameters Scenario 2 upon first execution Parameters are passed such that the IF condition executes ONLY Block1 is optimized. Block2 will be optimized when a parameter which forces the ELSE condition is passed.
See ModularProcedures.sql
sp_recompile
Can be used to periodically and directly force recompilation of a procedure (or trigger) Can be used on tables and views to indirectly force the recompilation of all procedures and triggers that reference the specified table or view Does not actually recompile the procedures Instead it invalidates plans for next execution SQL Server invalidates plans as data changes Never really negative especially if you run it at night as part of batch processing after index rebuilds or statistics updates with FULLSCAN
Naming Conventions
Owner Qualify to Eliminate Ambiguity
On execution
EXEC dbo.procname
On creation
CREATE PROC dbo.procname AS SELECT columnlist FROM dbo.tablename EXEC dbo.procname
Minimize Blocking initial cache lookup by owner will fail. It will not cause a recompile but excessive lookups can cause significant blocking and cache misses. Do not use sp_ in stored procedure names causes cache misses on lookup as well because SQL Server looks in master first!
See KB Article Q263889
Modifying Procedures
DROP and RECREATE
Loses the dependency chain stored in sysdepends Loses the permissions already granted Invalidates all plans
ALTER PROC
Loses the dependency chain stored in sysdepends Retains the permissions Invalidates all plans
To retain the dependency chain you must also ALTER all procedures that depend on the procedure being altered.
Recommendation: DO NOT Change these session settings in the client or the server! See SET Options that Affect Results in the BOL
Data Manipulation
Derived Tables
Nested Subquery in FROM clause May optimize better than temp tables/variables
Views
Another option rewrite existing temp table code to use views instead (simple rewrite) May optimize better than temp tables/variables
Temp Tables
Should be considered
Table Variables
Limitations might not affect you Might be the most optimal
Population
Does not support INSERT EXEC Does not support SELECT INTO
CONs
Potential for excessive recompiles due to resolution
CONs
Cannot create additional nonclustered indexes Not flexible on population
Detecting SP Recompilation
Event = SP:Recompile & Column = EventSubClass
Local Schema, bindings or permissions changed between compile and execute or executions
Shouldnt happen often. If it does isolate where/how changes occur and batch/schedule for off hours
Statistics changed
Thresholds for statistics of the different types of tables vary. Empty Tables (Permanent >= 500, Temp >= 6, Table Variables = No threshold) Tables with Data (Perm/Temp >= 500 + 20% cardinality, Table Variables = No threshold) If consistent plan then eliminate recompiles from changes in statistics by using (KEEPFIXED PLAN) optimizer hint in SELECT
3 4 5 6
Profiling SP Performance
Create New Trace (SQLProfilerTSQL_sps)
Replace SP:StmtStarting w/SP:StmtCompletion Better if you want to see a duration (starting events dont have a duration) Add Duration as a Column Value
Review
Initial Processing - Review
Resolution Compilation/Optimization Execution/Recompilation
Recompilation Issues
When do you want to Recompile? Options for Recompilation? What to Recompile?
Other Sessions
DAT 335 SQL Server Tips and Tricks for DBAs and Developers Tuesday, 1 July 2003, 15:15-16:30 DBA 324 Designing for Performance: Structures, Partitioning, Views and Constraints Wednesday, 2 July 2003, 08:30-09:45 DBA 328 Designing for Performance: Optimization with Indexes Wednesday, 2 July 2003, 16:45-18:00 DBA 322 Optimizing Stored Procedure Performance in SQL Server 2000 Thursday, 3 July 2003, 08:30-09:45
Articles
Articles in TSQLSolutions at www.tsqlsolutions.com (FREE, just register)
All About Raiserror, InstantDoc ID#22980 Saving Production Data from Production DBAs, InstantDoc ID#22073
Resources
Whitepaper: Query Recompilation in SQL Server 2000 http://msdn.microsoft.com/library/default.asp? url=/nhp/Default.asp?contentid=28000409
Community Resources
Community Resources
http://www.microsoft.com/communities/default.mspx
Newsgroups
Converse online with Microsoft Newsgroups, including Worldwide http://www.microsoft.com/communities/newsgroups/default.mspx
User Groups
Meet and learn with your peers http://www.microsoft.com/communities/usergroups/default.mspx
Thank You!
Kimberly L. Tripp
Principal Mentor, Solid Quality Learning
Website: www.SolidQualityLearning.com Email: Kimberly@SolidQualityLearning.com
Available
7/9/03
Today
Microsoft Press books are 20% off at the TechEd Bookstore Also buy any TWO Microsoft Press books and get a FREE T-Shirt
evaluations
2003 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.