Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script that provides the row counts and table names

Tags:

sql

sql-server

Maybe you easily said how to I provide table names and row counts?

Pseudo SQL:

for "select tablename from system.Tables" into :tablename
  execute "select count(*) from ? into ?" using :tablename, :count
  return row(:tablename, :count)
end for

Can you tell me show me this script in T-SQL?

like image 834
durumdara Avatar asked Mar 31 '12 09:03

durumdara


People also ask

How do I get the row count in a table in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

What is the method to count the number of rows in a table?

The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.


1 Answers

If you're on SQL Server 2005 or newer (you unfortunately didn't specify which version of SQL Server you're using), this query should give you that information:

SELECT 
    TableName = t.NAME,
    TableSchema = s.Name,
    RowCounts = p.rows
FROM 
    sys.tables t
INNER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE 
    t.is_ms_shipped = 0
GROUP BY
    t.NAME, s.Name, p.Rows
ORDER BY 
    s.Name, t.Name

This produces an output something like (this is from AdventureWorks):

TableName       TableSchema      RowCounts
AWBuildVersion    dbo                  1
DatabaseLog       dbo               1597
ErrorLog          dbo                  0
Department        HumanResources      16
Employee          HumanResources     290
JobCandidate      HumanResources      13
Address           Person           19614
AddressType       Person               6
... and so on......
like image 72
marc_s Avatar answered Oct 02 '22 22:10

marc_s