Technical Article

FASTCOUNT() User-Defined Function (SQL 2000 only)

,

SQL Server's COUNT() function is a slow and expensive way to count a table's rows because it scans the entire table or index.  FASTCOUNT(), which I created, is much more efficient for this purpose - its only drawback being that it may return inaccurate results if a nonlogged (e.g., bulk) data modification operation was recently performed against the table.

Syntax: SELECT dbo.FASTCOUNT('')

Because this is a function, you can use it "inline" in any SQL statement or script, just as you would use COUNT(); however, there are some syntax differences.

Unlike COUNT(), FASTCOUNT() takes a table name as its argument (rather than a column name or wildcard), instead of requiring you to suply the table name in a FROM clause.  The advantage of this is that you can pass a variable as table name without resorting to dynamic SQL.  In other words, the following command is legal:

DECLARE @Tbl sysname
SET @Tbl = 'MyTable'
SELECT dbo.FASTCOUNT(@Tbl)

(If you were to accomplish the same results with COUNT(), you would need to use dynamic SQL to pass the table name into a FROM clause).

CREATE FUNCTION FASTCOUNT (@Table sysname)

RETURNS INT

AS
BEGIN

  DECLARE @Rows int

  SELECT  @Rows = rows 
  FROM sysindexes
  WHERE id = OBJECT_ID(@Table)
  AND indid < 2

  RETURN @Rows

END

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating