uncoditioned Count(*) vs System tables(未编码的 Count(*) 与系统表)
问题描述
我的一个同事给我看的比,要数一个表的记录,如下视图:
A collegue of mine show me than, to count a record of a table, the following view:
CREATE VIEW [SPR].[TablesCount]
AS
SELECT s.name cSchema,
t.name cTable,
sum(p.rows) eRowCount
FROM sys.tables t
INNER JOIN sys.schemas s
ON s.schema_id = t.schema_id
INNER JOIN SYS.partitions p
ON p.object_id = t.object_id
WHERE p.index_id < 2
GROUP BY s.name,
t.name
执行速度明显快于常规
select count(*) from table
这是为什么?不应该优化数据库引擎以始终遵循最短路径吗?系统表视图解决方案的缺点是什么?
why this? shouldn't the db engine be optimized to follow the shortest path always? What's the drawback in the system tables view solution?
推荐答案
不保证存储在元数据中的值是正确的.DBCC UPDATEUSAGE 可用于在它发生时更正(更少可能从 SQL Server 2000 开始)
The value stored in the metadata is not guaranteed to be correct. DBCC UPDATEUSAGE can be used to correct this when it happens (less likely since SQL Server 2000)
它也不是事务一致的.您可以读取由未提交事务更新的计数值.
Also it is not transactionally consistent. You can read a count value updated by an uncommitted transaction.
这些值也可以手动更新.
And it is possible for these values to be manually updated as well.
CREATE TABLE dbo.YourTable(X INT)
UPDATE STATISTICS dbo.YourTable WITH ROWCOUNT = 1000000
SELECT sum(p.rows) eRowCount
FROM sys.partitions p
WHERE P.object_id =object_id('dbo.YourTable') AND p.index_id < 2
这篇关于未编码的 Count(*) 与系统表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:未编码的 Count(*) 与系统表
基础教程推荐
- oracle区分大小写的原因? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在多列上分布任意行 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
