Wednesday, October 29, 2008

Getting Stats from SQL Server via Query

For a long time now, I use references to the sysobjects table to get some stats on databases that are being catalogued for a database migration (or for just cataloguing in general). Anyways, I open up Query Analyzer (SQL 2000) or a new Query window (SQL 2005/2008) and use variations of the following code examples:

-- Counts all the tables in a database
SELECT [Count] = count(so.name)
FROM sysobjects so
WHERE so.xtype = 'U'

-- Counts all stored procedures in a database
SELECT [Count] = count(so.name)
FROM sysobjects so
WHERE so.xtype = 'P'
-- Returns the count of main database objects
SELECT [Tables] = count(so.name)FROM sysobjects so WHERE so.xtype = 'U' AND left(so.type,2) <> 'dt'
SELECT [StoredProcs] = count(so.name)FROM sysobjects so WHERE so.xtype = 'P' AND left(so.type,2) <> 'dt'
SELECT [Views] = count(so.name)FROM sysobjects so WHERE so.xtype = 'V' AND left(so.type,2) <> 'dt'
SELECT [Triggers] = count(so.name)FROM sysobjects so WHERE so.xtype = 'TR' AND left(so.type,2) <> 'dt'
SELECT [ExtendedStoredProcs] = count(so.name)FROM sysobjects so WHERE so.xtype = 'X' AND left(so.type,2) <> 'dt'
This is the list of all possible values for this column (xtype):
  • C = CHECK constraint
  • D = Default or DEFAULT constraint
  • F = FOREIGN KEY constraint
  • L = Log
  • P = Stored procedure
  • PK = PRIMARY KEY constraint (type is K)
  • RF = Replication filter stored procedure
  • S = System table
  • TR = Trigger
  • U = User table
  • UQ = UNIQUE constraint (type is K)
  • V = View
  • X = Extended stored procedure