Created
March 26, 2019 22:41
-
-
Save stummsft/7bb9b5059ae5e4faf1208d77ee53a10a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* This function will return all plan_handles that include a reference to | |
* a given object. This can help with targeted purges of execution plans. | |
*/ | |
CREATE OR ALTER FUNCTION find_query_plans_by_object ( | |
@database SYSNAME, | |
@schema SYSNAME, | |
@table SYSNAME | |
) RETURNS TABLE | |
AS | |
RETURN | |
WITH XMLNAMESPACES ( | |
default 'http://schemas.microsoft.com/sqlserver/2004/07/showplan' | |
) | |
SELECT | |
query_stats.plan_handle | |
FROM ( | |
SELECT DISTINCT plan_handle | |
FROM sys.dm_exec_query_stats | |
) query_stats | |
CROSS APPLY sys.dm_exec_query_plan(query_stats.plan_handle) qp | |
WHERE | |
qp.query_plan.exist('//ColumnReference[ | |
(empty(sql:variable("@database")) or @Database eq sql:variable("@database") or @Database eq fn:concat("[", sql:variable("@database"), "]")) | |
and (empty(sql:variable("@schema")) or @Schema eq sql:variable("@schema") or @Schema eq fn:concat("[", sql:variable("@schema"), "]")) | |
and (empty(sql:variable("@table")) or @Table eq sql:variable("@table") or @Table eq fn:concat("[", sql:variable("@table"), "]")) | |
]') = 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
SELECT *
FROM find_query_plans_by_object(NULL, 'dbo', 'tags')