Background:
I was investigating the fact that 'Table variables result in fewer re-compilations of a stored procedure as compared to temporary tables' which is mentioned in my another post 'Temp Table in SQL Server'. Than found two very good references (References-1 & 2) and felt like consolidating into fewer lines.
Query Plan related to Stored Procedure – Steps:
- The Stored Procedure is executed
- Check in cache to see it’s available
- If not available in cache,
- Load the Stored Procedure
- Compile the query plan
- Save compiled plan in cache
- Reuse by subsequent calls until the plan is invalidated and forced to recompile
Reason a Stored Procedure is recompiled:
- Use of a WITH RECOMPILE clause in the CREATE PROCEDURE or EXECUTE statement.
- Schema changes to any of the referenced objects, including adding or dropping constraints, defaults, or rules.
- Running sp_recompile for a table referenced by the procedure.
- Restoring the database containing the procedure or any of the objects the procedure references (if you are performing cross-database operations).
- Sufficient server activity causing the plan to be aged out of cache
- A sufficient percentage of data changes in a table that is referenced by the stored procedure
- Ways to counteract recompilation
i. Execute the statement using sp_executesql - Statements executed using the sp_executesql stored procedure are not compiled as part of the stored procedure plan
ii. Use sub-procedures to execute the statements that are causing the recompilations - the statement may still cause a recompilation, but instead of recompiling the large calling stored procedure, it will only recompile the small sub-procedure
iii. Use the KEEP PLAN option
- The procedure interleaves Data Definition Language (DDL) and Data Manipulation Language (DML) operations.
- The procedure performs certain operations on temporary tables
- Ways to counteract recompilation
i. All statements that contain the name of a temporary table refer to a temporary table created in the same stored procedure, and not in a calling or called stored procedure, or in a string executed using the EXECUTE statement or sp_executesql stored procedure
ii. All statements that contain the name of a temporary table appear syntactically after the temporary table in the stored procedure or trigger.
iii. There are no DECLARE CURSOR statements whose SELECT statements reference a temporary table
iv. All statements that contain the name of any temporary table precede any DROP TABLE statement that references a temporary table
References:
No comments:
Post a Comment