'UDF'에 해당되는 글 1건

  1. 2008.09.11 select count(*) from Table 을 빠르게 하는 법
Study/Mssql2008. 9. 11. 16:18


 

단순한 Table Count를 하기 위해서 보통
select count(*) from TableName
을 사용한다..
이럴경우 전체 테이블을 인덱스 스캔을 하게 되고 Stream Aggregate을 시행한다..
데이타가 많지 않을 경우는 괜찮겠지만..
몇백만 몇천만의 데이타일 경우는 문제가 쪼까 되겄지..

SQL Server 2005에서 제공하는 시스템 카테고리 뷰를 가지고 UDF를 만들어서 빠르게 할수가 있다..

CREATE 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) -- 0 heap table , 1 table with clustered index
       and p.rows is not null
  and a.type = 1  -- row-data only , not LOB
  and p.object_id = object_id(@table_name)    
 END 
RETURN (@nn)
END
GO


select dbo.row_count ('Sales.SalesOrderDetail')
go
select count (*) from Sales.SalesOrderDetail
go



 

 

Cost가 거의 10분의 1로 줄어든다.. ^^

내가 테스트 하기론 한 100배는 빨라지는거 같다..





Posted by 영혼도둑