SQL Server Max ID and Row Count

This is how to get the Max ID and the Row Count for all tables in a SQL Database. It's a good way to check that things look OK!

The MaxValues should not be wildly, more than the row count unless you know that rows have been deleted constantly, like the use of a temp table for example.

SELECT DISTINCT 
	   SchemaName = SCHEMA_NAME(CAST(OBJECTPROPERTYEX(sc.object_id,'SchemaId')AS INT))
      ,ObjectName = OBJECT_NAME(sc.object_id)
      ,ColumnName = sc.name
      ,DataType = TYPE_NAME (sc.system_type_id)
      ,MaxValue = sc.last_value
	  ,NoOfRows = p.rows
  FROM sys.identity_columns sc
  INNER JOIN 
    sys.partitions p ON sc.object_id = p.OBJECT_ID 
 WHERE OBJECTPROPERTYEX(sc.object_id,'IsTable') = 1
   AND SCHEMA_NAME(CAST(OBJECTPROPERTYEX(sc.object_id,'SchemaId')AS INT)) LIKE 'dbo'
 ORDER BY MaxValue DESC, ObjectName

 

Add comment

Loading