易丰科技

标题: 列示资料库裹各资料表的资料笔数 [打印本页]

作者: Calvin    时间: 2011-10-7 10:27
标题: 列示资料库裹各资料表的资料笔数
  1. SELECT
  2.     [TableName] = so.name,
  3.     [RowCount] = MAX(si.rows)
  4. FROM
  5.     sysobjects so,
  6.     sysindexes si
  7. WHERE
  8.     so.xtype = 'U'
  9.     AND
  10.     si.id = OBJECT_ID(so.name)
  11. GROUP BY
  12.     so.name
  13. ORDER BY
  14.     2 DESC
复制代码


作者: Calvin    时间: 2011-10-7 10:31
另一种方式
  1. CREATE PROCEDURE dbo.listTableRowCounts
  2. AS
  3. BEGIN
  4.     SET NOCOUNT ON
  5.     DECLARE @SQL VARCHAR(255)
  6.     SET @SQL = 'DBCC UPDATEUSAGE (' + DB_NAME() + ')'
  7.     EXEC(@SQL)
  8.     CREATE TABLE #foo
  9.     (
  10.         tablename VARCHAR(255),
  11.         rc INT
  12.     )
  13.      
  14.     INSERT #foo
  15.         EXEC sp_msForEachTable
  16.             'SELECT PARSENAME(''?'', 1),
  17.             COUNT(*) FROM ?'
  18.     SELECT tablename, rc
  19.         FROM #foo
  20.         ORDER BY rc DESC
  21.     DROP TABLE #foo
  22. END
复制代码

作者: Calvin    时间: 2011-10-7 10:34
标题: 第三种方式 user defined function
  1. CREATE FUNCTION dbo.udf_Tbl_RowCOUNT (

  2.         @sTableName sysname  -- Table to retrieve Row Count
  3.         )

  4.     RETURNS INT -- Row count of the table, NULL if not found.

  5. /*
  6. * Returns the row count for a table by examining sysindexes.
  7. * This function must be run in the same database as the table.
  8. *
  9. * Common Usage:   
  10. SELECT dbo.udf_Tbl_RowCOUNT ('')

  11. * Test   
  12. PRINT 'Test 1 Bad table ' + CASE WHEN SELECT
  13.        dbo.udf_Tbl_RowCOUNT ('foobar') is NULL
  14.         THEN 'Worked' ELSE 'Error' END
  15.         
  16. * © Copyright 2002 Andrew Novick http://www.NovickSoftware.com
  17. * You may use this function in any of your SQL Server databases
  18. * including databases that you sell, so long as they contain
  19. * other unrelated database objects. You may not publish this
  20. * UDF either in print or electronically.
  21. ***************************************************************/

  22. AS BEGIN
  23.    
  24.     DECLARE @nRowCount INT -- the rows
  25.     DECLARE @nObjectID int -- Object ID

  26.     SET @nObjectID = OBJECT_ID(@sTableName)

  27.     -- Object might not be found
  28.     IF @nObjectID is null RETURN NULL

  29.     SELECT TOP 1 @nRowCount = rows
  30.         FROM sysindexes
  31.         WHERE id = @nObjectID AND indid < 2

  32.     RETURN @nRowCount
  33. END
  34. GO

  35. GRANT  EXECUTE  ON [dbo].[udf_Tbl_RowCOUNT]  TO PUBLIC
  36. GO
复制代码
使用方式
  1. use pubs -- assuming the UDF was created in pubs
  2. go

  3. SELECT [name]
  4.      , dbo.udf_Tbl_RowCOUNT ([name]) as [Row Count]
  5.     FROM sysobjects
  6.     WHERE type='U' and name != 'dtproperties'
  7.     ORDER BY [name]
  8. GO
复制代码







欢迎光临 易丰科技 (http://forum.yftek.com/) Powered by Discuz! X3