Creating Uncacheable Stored Procedures In SQL Server
Here’s the demo script from today’s video:
/*Create a table if you need to*/ CREATE TABLE dbo.DinnerPlans ( id bigint IDENTITY, name nvarchar(40) NOT NULL, seat_number tinyint NULL, is_free bit NOT NULL, ); GO /*First example, with an object that doesn't exist*/ CREATE OR ALTER PROCEDURE dbo.i_live ( @decider bit = NULL ) AS BEGIN SET NOCOUNT, XACT_ABORT ON; IF @decider = 'true' BEGIN SELECT dp.* FROM dbo.DinnerPlans AS dp; END; IF @decider = 'false' BEGIN SELECT whatever.* FROM dbo.AnObjectThatDoesntEvenPretendToExist AS whatever; --SELECT result = 'false!'; END; IF @decider IS NULL BEGIN SELECT result = 'please make a decision.' END; END; GO /*Say goodbye!*/ DBCC FREEPROCCACHE; /*This runs without an error*/ EXEC dbo.i_live @decider = 'false'; /*But there's no query plan!*/ SELECT object_name = OBJECT_NAME(deps.object_id, deps.database_id), deps.type_desc, deps.last_execution_time, deps.execution_count, dest.text, query_plan = TRY_CAST(detqp.query_plan AS xml) FROM sys.dm_exec_procedure_stats AS deps OUTER APPLY sys.dm_exec_sql_text(deps.plan_handle) AS dest OUTER APPLY sys.dm_exec_text_query_plan(deps.plan_handle, 0, -1) AS detqp; GO
Thanks for watching!
Going Further
If this is the kind of SQL Server stuff you love learning about, you’ll love my training. I’m offering a 75% discount to my blog readers if you click from here. I’m also available for consulting if you just don’t have time for that, and need to solve database performance problems quickly. You can also get a quick, low cost health check with no phone time required.