Script that provides the row counts and table names - sql

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?

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......

SELECT
t.NAME AS TableName, p.[Rows] FROM
sys.tables t INNER JOIN
sys.partitions p ON t.object_id = p.OBJECT_ID GROUP BY
t.NAME, p.[Rows] ORDER BY t.NAME

-- Shows all user tables and row counts for the current database
-- Remove OBJECTPROPERTY function call to include system objects
SELECT o.NAME,
i.rowcnt
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
WHERE i.indid < 2 AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY o.NAME

exec sp_MSForEachTable 'SELECT ''?'' as TableName, COUNT(*) as Rows FROM ?'

I have adjusted the answer from marc_c with CTE and displaying it with choice of displaying just the schema you are after.
Should work with SQL Serve 2005 and newer.
WITH CountRowsInTables (Table_Name, Table_Schema, Row_Counts) AS
(
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
s.Name, t.Name, p.Rows
)
SELECT Table_name, Table_Schema, Row_Counts
FROM CountRowsInTables
WHERE Table_Schema = 'Pick_Schema_to_display';

Try this
-- drop table #tmpspace
create table #tmpspace (
name sysname
, rows int
, reserved varchar(50)
, data varchar(50)
, index_size varchar(50)
, unused varchar(50)
)
dbcc updateusage(0) with NO_INFOMSGS
exec sp_msforeachtable 'insert #tmpspace exec sp_spaceused ''?'''
select * from #tmpspace
order by convert(int, substring(reserved, 1, charindex(' ', reserved))) desc, rows desc, name
Works on sql2000 too.
dbcc updateusage might take some time but results will be 100% actual. Skip it if you need speed over accuracy.

This works for me:
SELECT sc.name +'.'+ ta.name TableName
,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC

Related

SqlServer - Get all tables that has data ( are not empty )

The question is simple:
Is it possible to retrive all the tables that are not empty ?
I need a query to list the tables. Is there a way ?
Thanks to support
Try this Script To get all tables with non empty records
USE [Your database Name]
Go
SELECT SCHEMA_NAME(schema_id) AS [SchemaName],
[Tables].name AS [TableName]
--SUM([Partitions].[rows]) AS [TotalRowCount]
FROM sys.tables AS [Tables]
JOIN sys.partitions AS [Partitions]
ON [Tables].[object_id] = [Partitions].[object_id]
AND [Partitions].index_id IN ( 0, 1 )
-- WHERE [Tables].name = N'name of the table'
GROUP BY SCHEMA_NAME(schema_id), [Tables].name
HAVING SUM([Partitions].[rows]) >0
Slightly different than #Sreenu131 answer as it is using sys.partitions .rows property to find
p.rows > 0
SELECT
sch.name as SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts
FROM
sys.tables t
INNER JOIN
sys.partitions p ON t.object_id = p.OBJECT_ID
INNER JOIN sys.schemas sch
on t.schema_id = sch.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND p.rows > 0
GROUP BY
sch.name,t.Name, p.Rows
ORDER BY
sch.name,t.Name

SQL Server index usage stats

I have run the query below in order to find indexes to delete.
SELECT d.name AS DatabaseName, t.name AS TableName, i.name AS IndexName, ius.*
FROM sys.dm_db_index_usage_stats ius
JOIN sys.databases d ON d.database_id = ius.database_id
JOIN sys.tables t ON t.object_id = ius.object_id
JOIN sys.indexes i ON i.object_id = ius.object_id AND i.index_id =
ius.index_id
ORDER BY user_updates DESC
But the result set that returns is pretty confusing. I am receiving multiple rows for the same indexes with different database_ids and therefore names. Let's say we have an index and its name is IDXName and its is IDXID. This index is under TBL1 inthe DB1 database. But there are multiple rows for this index with same index name and same index id and same table name but different database ids.
I double checked the Microsoft documentation and it confirms that the database id in that view is the database where the index resides. So how come I have the ids of the databases that that index does not exist in?
Yoy didn't linit the query to current database, that's why you're seeing data on indexes from different databases:
SELECT d.name AS DatabaseName, t.name AS TableName, i.name AS IndexName, ius.*
FROM sys.dm_db_index_usage_stats ius
JOIN sys.databases d ON d.database_id = ius.database_id
JOIN sys.tables t ON t.object_id = ius.object_id
JOIN sys.indexes i ON i.object_id = ius.object_id AND i.index_id = ius.index_id
WHERE d.database_id = db_id()
ORDER BY user_updates DESC
If all you need from sys.databases is a database name, there's no need for the join at all:
SELECT db_name() AS DatabaseName, t.name AS TableName, i.name AS IndexName, ius.*
FROM sys.dm_db_index_usage_stats ius
JOIN sys.tables t ON t.object_id = ius.object_id
JOIN sys.indexes i ON i.object_id = ius.object_id AND i.index_id = ius.index_id
WHERE ius.database_id = db_id()
ORDER BY user_updates DESC

Row count for tables in a specific schema [duplicate]

This question already has answers here:
Get counts of all tables in a schema
(6 answers)
Closed 9 years ago.
How to get a sql query which will get me all the tables with their respect row counts within one schema
Below is the Microsoft SQL Server query to retrieve all Tables what the schema is for the table and the amount of rows.
to use for specific schema simply uncomment the last row of there where clause(remove /**/). and enter the schema names that you are looking for in the brackets on the last row of the where clause you can enter more then 2 just simply follow the pattern 'SchemaName','SchemaName','SchemaName'.
SELECT
t.NAME AS TableName,
s.name AS SchemaName,
p.[Rows]
FROM
sys.tables t
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
INNER JOIN
sys.schemas s on s.schema_id = t.schema_id
WHERE
t.NAME NOT LIKE 'dt%' AND
i.OBJECT_ID > 255 AND
i.index_id <= 1 /* AND
s.name in ('Schemaname1','Schemaname2') */
GROUP BY
t.NAME, i.object_id, i.index_id, i.name,s.name, p.[Rows]
ORDER BY
object_name(i.object_id)
if you would like to query like this
SELECT owner, table_name, NUM_ROWS FROM ALL_TABLES where owner like 'Schema_name'
I would suggest creating a view like so.
CREATE VIEW ALL_TABLES
AS
SELECT
t.NAME AS table_name,
s.name AS owner,
p.[Rows] as NUM_ROWS
FROM
sys.tables t
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
INNER JOIN
sys.schemas s on s.schema_id = t.schema_id
WHERE
t.NAME NOT LIKE 'dt%' AND
i.OBJECT_ID > 255 AND
i.index_id <= 1 /* AND
s.name in ('Schemaname1','Schemaname2') */
GROUP BY
t.NAME, i.object_id, i.index_id, i.name,s.name, p.[Rows]
ORDER BY
object_name(i.object_id)
and then if you run the following query it will work
SELECT owner, table_name, NUM_ROWS FROM ALL_TABLES where owner like 'Schema_name'
If this helps please mark the answer as correct

Can I find which indexes are current / in use

I have the following:
SELECT name AS index_name,
STATS_DATE(OBJECT_ID, index_id) AS StatsUpdated
FROM sys.indexes
Is it possible to add some information so I have an idea if each index is current and in use?
Also I'd like to return in the SELECT clause which table the index is on?
I am using the following query to find if an index is is use - if seeks,scans and look-ups are zero then it's not used.
SELECT TOP 25
o.name AS ObjectName
, i.name AS IndexName
, i.index_id AS IndexID
, dm_ius.user_seeks AS UserSeek
, dm_ius.user_scans AS UserScans
, dm_ius.user_lookups AS UserLookups
, dm_ius.user_updates AS UserUpdates
, p.TableRows
, is_disabled
,STATS_DATE(i.[OBJECT_ID], i.index_id) AS StatsUpdated
FROM sys.dm_db_index_usage_stats dm_ius
INNER JOIN sys.indexes i ON i.index_id = dm_ius.index_id AND dm_ius.object_id = i.object_id
INNER JOIN sys.objects o on dm_ius.object_id = o.object_id
INNER JOIN sys.schemas s on o.schema_id = s.schema_id
INNER JOIN (SELECT SUM(p.rows) TableRows, p.index_id, p.object_id
FROM sys.partitions p GROUP BY p.index_id, p.object_id) p
ON p.index_id = dm_ius.index_id AND dm_ius.object_id = p.object_id
WHERE OBJECTPROPERTY(dm_ius.object_id,'IsUserTable') = 1
AND dm_ius.database_id = DB_ID()
AND i.type_desc = 'nonclustered'
AND i.is_primary_key = 0
AND i.is_unique_constraint = 0
ORDER BY (dm_ius.user_seeks + dm_ius.user_scans + dm_ius.user_lookups) ASC
GO

Selecting Rowcount and number of columns with one sql query?

How can i club both the select count and select columns with one statement?
If you are just looking to see what "shape" your tables are in, something like this would work. But if you're wanting to know column/row counts for a given query, it may be possible but I don't know how to do it
; WITH ROW_COUNTS AS
(
SELECT
s.[Name] as [SchemaName]
, t.[name] as [TableName]
, SUM(p.rows) as [RowCounts]
FROM
sys.schemas s
LEFT JOIN
sys.tables t
ON s.schema_id = t.schema_id
LEFT JOIN
sys.partitions p
ON t.object_id = p.object_id
LEFT JOIN
sys.allocation_units a
ON p.partition_id = a.container_id
WHERE
p.index_id in(0,1) -- 0 heap table , 1 table with clustered index
AND p.rows is not null
AND a.type = 1 -- row-data only , not LOB
GROUP BY
s.[Name]
, t.[name]
)
, COLUMN_COUNTS AS
(
SELECT
s.[Name] as [SchemaName]
, t.[name] as [TableName]
, COUNT(c.column_id) as [ColumnCounts]
FROM
sys.schemas s
INNER JOIN
sys.tables t
ON s.schema_id = t.schema_id
INNER JOIN
sys.columns c
ON C.object_id = T.object_id
GROUP BY
s.[Name]
, t.[name]
)
SELECT
CC.SchemaName
, CC.TableName
, RC.RowCounts
, CC.ColumnCounts
FROM
COLUMN_COUNTS CC
INNER JOIN
ROW_COUNTS RC
ON RC.SchemaName = CC.SchemaName
AND RC.TableName = CC.TableName
ORDER BY
1,2
Results run against master
SchemaName TableName RowCounts ColumnCounts
dbo Hold_Cluster_Status 0 10
dbo MSreplication_options 3 6
dbo spt_fallback_db 0 8
dbo spt_fallback_dev 0 10
dbo spt_fallback_usg 0 9
dbo spt_monitor 1 11
dbo spt_values 2506 6
Using a COUNT() window aggregate you should be able to accomplish what you are looking to do. However, the DISTINCT against a very large table is not likely to be very performant:
SELECT DISTINCT a, b, c, COUNT(*) OVER (PARTITION BY 1) FROM <tablename>;
Another option would be but you are touching the table twice:
SELECT a,b,c, MyCount
FROM <tablename>
CROSS JOIN
(SELECT COUNT(*) AS MyCount
FROM <tablename>
)
I'm not 100% ure what you want, but here is a possible example...
SELECT
a,
b,
c,
(SELECT COUNT(*) FROM yourTable) as table_count
FROM
yourTable