-
-
Save erikdarlingdata/dd6da1714f17255970afabc6556bb1e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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; | |
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 = 'true'; | |
/*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 | |
/*Second example, without 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 /*Skipparoo*/ | |
false = 'this is false'; | |
END; | |
IF @decider IS NULL | |
BEGIN | |
SELECT | |
result = 'please make a decision.' | |
END; | |
END; | |
GO | |
/*Say goodbye!*/ | |
DBCC FREEPROCCACHE; | |
/*This obviously runs without an error*/ | |
EXEC dbo.i_live | |
@decider = 'true'; | |
/*Now there's a 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment