Info |
---|
Looking for a smart way to count all rows in all tables in your db or schema? Use this script |
You can simply use the script as is, or deploy for persistent use. The parameter will enable you to define a schema, just execute as null for schema agnostic:
Paste code macro |
---|
|
Create Procedure sp_All_Table_Row_Count (@schema Varchar(100)) As
/*
Create the holding table:
This |
...
Use this to prevent being shoe-horned into the newer method which has a severly limited editing experience.
Usage is simple:
- Do not enter editing mode and choose copy from the elipses in the top-right corner
- in the newly copied page, alter the page parent to "Visualisation Success with Tableau" even if only temporary
- add some new text to this page and publish
- Now re-enter and adjust the title to your chosen title and publish
- You are now ready to build the page - go on and edit in your own time, deleting everything above and including the "Delete Me" line below
...
table is important as it will contain the list of tables,
their row counts, and the ID which is the main driver for the loop
*/
If Object_ID('tempdb..#Table_of_Tables') Is Not Null Drop Table #Table_of_Tables
Create Table #Table_of_Tables (
ID Int Identity(1,1) Not Null
,Table_Name Varchar(200) Not Null
,Row_Count BigInt Null
)
-- Get the list of tables and insert into the table_of_tables
-- This will not include the system-generated tables; remove the Where clause for all tables
Insert Into #Table_of_Tables
Select
t.[name]
,Null
From sys.tables t
Join sys.schemas s On t.schema_id = s.schema_id
Where s.[name] = Coalesce(@schema, s.[name]) And t.type_desc = 'USER_TABLE'
-- Begin the looping
Declare @counter Int
Declare @EndRow Int -- By using a parameter, we can negate the need for re-querying on each loop
Declare @tname Varchar(200)
Declare @sql nVarchar(250)
Set @counter = 1
Select @EndRow = Max(ID)+1 From #Table_of_Tables
While @counter < @EndRow
Begin
Select @tname = Table_Name From #Table_of_Tables Where ID = @counter
-- Temp table to hold the row count
If Object_ID('tempdb..##RCount') Is Not Null Drop Table ##RCount
Select @sql = Replace('Select Count(1) As Row_Count Into ##RCount From @table','@table',@tname)
Exec sp_ExecuteSQL @sql
Update a
Set a.Row_Count = (Select Row_Count From ##RCount)
From #Table_of_Tables a
Where a.ID = @counter
Set @sql = Null
If Object_ID('tempdb..##RCount') Is Not Null Drop Table ##RCount
Set @counter = @counter +1
End;
-- Final clean-up, move data to a temp table and drop the actual table
Select Table_Name, Row_Count From #Table_of_Tables Order By Table_Name |
Usage Examples:
Paste code macro |
---|
language | sql |
---|
title | All tables |
---|
|
Exec sp_All_Table_Row_Count null |
Paste code macro |
---|
language | sql |
---|
title | All tables from dbo schema |
---|
|
Exec sp_All_Table_Row_Count 'dbo' |
Paste code macro |
---|
language | sql |
---|
title | All tables from sales schema |
---|
|
Exec sp_All_Table_Row_Count 'sales' |