Skip to content
Advertisement

SQL get row count from every table tenantwise

I am working on a multitenant application. Most of the tables contain a column tenant_id. I want the number of rows in all tables for a particular tenant_id.

Example, Tables:-

Sample result to get number of rows in every table having tenantid = 64

TableName Count
Employee 2
Student 3
Teacher 1

How do I loop through all the tables and query where tenantid = <tenantid>

Advertisement

Answer

Use Dynamic Query. Form the query dynamically for each table and use string_agg() to concatenate it and execute the query using sp_executesql

db<>fiddle demo

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement