未编码的 Count(*) 与系统表 [英] uncoditioned Count(*) vs System tables

查看:27
本文介绍了未编码的 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(*) 与系统表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆