更改数据库范围的配置 清除PROCEDURE_CACHE不删除缓存?



我有一个 azure PaaS 数据库,想清除缓存以测试一些 SP。所以我从网上找到了一些脚本:

-- run this script against a user database, not master
-- count number of plans currently in cache
select count(*) from sys.dm_exec_cached_plans;
-- Executing this statement will clear the procedure cache in the current database, which means that all queries will have to recompile.
ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;
-- count number of plans in cache now, after they were cleared from cache
select count(*) from sys.dm_exec_cached_plans;
-- list available plans
select * from sys.dm_exec_cached_plans;
select * from sys.dm_exec_procedure_stats 

但是,缓存量始终在 600-800 左右,因此不知何故它不会下降。

我没有收到任何错误(没有权限被拒绝等(,那么这个命令如何不清理缓存?

我没有时间调试代码以 100% 确定,但根据我对系统的理解,很可能仅仅增加数据库架构版本(发生在任何更改数据库命令上(将使缓存中的条目在下次使用时失效。 由于过程缓存是实例范围的,因此任何清除与数据库关联的条目的尝试都需要逐个遍历所有条目,而不仅仅是释放整个缓存。

因此,您可以将其视为使整个缓存无效,但在重新编译条目时或如果内存由系统的其他部分通过后续操作回收时,会延迟地从缓存中删除条目。

康纳·坎宁安 架构师,SQL

我联系了Microsoft支持人员,现在明白了。

尝试在 AdventureWorks 数据库上运行以下 T-SQL。

-- create test procedure
create or alter procedure pTest1
as begin 
select * from salesLT.product where ProductCategoryID =27
end
go

-- exec the procedure once.
exec pTest1

-- check for cached plan for this specific procedure - cached plan exists
select * from sys.dm_exec_cached_plans p 
cross apply sys.dm_exec_sql_text(p.plan_handle) st
where p.objtype = 'proc' and st.objectid = OBJECT_ID('pTest1')

-- clear plan cache
ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;
-- check for cached plan for this specific procedure - not exists anymore
select * from sys.dm_exec_cached_plans p 
cross apply sys.dm_exec_sql_text(p.plan_handle) st
where p.objtype = 'proc' and st.objectid = OBJECT_ID('pTest1')

-- cleanup
drop procedure pTest1
select 'cleanup complete' 

通过此示例,我们可以确认已清除数据库的计划缓存,但是,sys.dm_exec_cached_plans是服务器范围的,并为您提供来自其他数据库(内部系统数据库(的结果,对于它们,未使用 CLEAR PROCEDURE_CACHE 命令清除缓存。

最新更新