正如其他人所展示的那样,您可以这样做,但不是像他们展示的那样使用COUNT,我将利用系统元数据,这要快得多。从物理上讲,调用SELECT COUNT(1) AS rc FROM MyTable 将强制存储引擎枚举所有可能在内存中或不在内存中的数据以执行计数并等待任何独占锁被解锁。
你知道什么更有效吗?只看 sys.allocation_units。
SELECT
s.[Name] as [Schema]
, t.[name] as [Table]
, SUM(p.rows) as [RowCount]
FROM
sys.schemas s
LEFT OUTER JOIN
sys.tables t
ON s.schema_id = t.schema_id
LEFT OUTER JOIN
sys.partitions p
ON t.object_id = p.object_id
LEFT OUTER JOIN
sys.allocation_units a
ON p.partition_id = a.container_id
WHERE
p.index_id in(0,1) -- 0 heap table , 1 table with clustered index
AND p.rows is not null
AND a.type = 1 -- row-data only , not LOB
GROUP BY
s.[Name]
, t.[name]
ORDER BY
1
, 2;
h/t 给 bimonkey 发帖 Count the number of rows in every Table in a Database in no time!
如果您想要一个执行此操作的“单一”查询,那么您需要将上述内容与您的偏移量和获取相结合。
在 SQL 中,不要将更少的代码行等同于更低的复杂性或更好的性能来愚弄。
我已经注释了以下查询,因为它真的很简单。
-- Create variables for our usage
-- http://technet.microsoft.com/en-us/library/ms188927.aspx
DECLARE @OFFSET int = 30
, @FETCH int = 15;
-- Notice the previous statement ends with a semicolon (;)
-- The following structure is a Common Table Expression (CTE)
-- Think of it as a single use View
-- http://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx
WITH COUNTS AS
(
-- This query provides the number of rows in all the tables
-- in the current catalog. It is screaming cheetah wheelies fast
-- as it does not need to physically read each row from each table
-- to generate counts. Instead, it is using system metadata to
-- derive the row count.
-- After the closing ), I will have access to a tabular structure
-- called COUNTS
SELECT
s.[Name] as [Schema]
, t.[name] as [Table]
, SUM(p.rows) as [RowCount]
FROM
-- http://technet.microsoft.com/en-us/library/ms176011.aspx
sys.schemas s
LEFT OUTER JOIN
-- http://technet.microsoft.com/en-us/library/ms187406.aspx
sys.tables t
ON s.schema_id = t.schema_id
LEFT OUTER JOIN
-- http://technet.microsoft.com/en-us/library/ms175012.aspx
sys.partitions p
ON t.object_id = p.object_id
LEFT OUTER JOIN
-- http://technet.microsoft.com/en-us/library/ms189792.aspx
sys.allocation_units a
ON p.partition_id = a.container_id
WHERE
p.index_id in(0,1) -- 0 heap table , 1 table with clustered index
AND p.rows is not null
AND a.type = 1 -- row-data only , not LOB
GROUP BY
s.[Name]
, t.[name]
)
SELECT
T.*
, @OFFSET AS StartingRow
, @FETCH AS PageSize
-- A subquery that uses the CTE above to extract our table's total row count
-- The table and schema below must align with the value in your FROM clause
-- http://technet.microsoft.com/en-us/library/ms189575(v=sql.105).aspx
, (SELECT C.[RowCount] FROM COUNTS C WHERE C.[schema] = 'dbo' AND C.[Table] = 'MyTable') AS TotalRows
FROM
dbo.MyTable T
ORDER BY
1
-- http://technet.microsoft.com/en-us/library/gg699618.aspx
OFFSET 30 ROWS
FETCH NEXT 15 ROWS ONLY;