每个数据库管理员知道如何使用count(*) 函数。SQL Server在执行这个函数时,为了返回总表的行计数,需要对索引/表进行完整的扫描。因此建议DBA们尽量避免针对整个表使用聚合函数count(*),因为它影响了数据库的性能。
在sql server 2005中,可以使用如下的函数row_count来代替 count(*) 以提高性能
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER FUNCTION [dbo].[row_count] (@table_name sysname)
-- @table_name we want to get count
RETURNS bigint
AS
BEGIN
DECLARE @nn bigint -- number of rows
IF @table_name IS NOT NULL
BEGIN
SELECT
@nn = sum( p.rows )
FROM sys.partitions p
LEFT JOIN sys.allocation_units a ON p.partition_id = a.container_id
WHERE
p.index_id in(0,1)
and p.rows is not null
and a.type = 1
and p.object_id = object_id(@table_name)
END
RETURN (@nn)
END
使用方法
declare @count int
set @count = dbo.row_count('T_SNETBlogArticle')
select @count