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:-
create table Employee(id integer, name varchar(100), tenantid integer);
insert into Employee(id, name, tenantid) values(1, "Stephan", 64);
insert into Employee(id, name, tenantid) values(2, "Alan", 64);
insert into Employee(id, name, tenantid) values(3, "Charles", 46);
create table Student(id integer, name varchar(100), standard integer, tenantid integer);
insert into Student(id, name, standard, tenantid) values(1, "James", 2, 64);
insert into Student(id, name, standard, tenantid) values(2, "Rony", 4, 64);
insert into Student(id, name, standard, tenantid) values(3, "Steve",6, 64);
create table Teacher(id integer, name varchar(100), subject varchar(100), tenantid integer);
insert into Teacher(id, name, subject, tenantid) values(1, "Alvin", "Science", 46);
insert into Teacher(id, name, subject, tenantid) values(2, "Neil", "Geography", 64);
insert into Teacher(id, name, subject, tenantid) values(3, "Amy", "Mathematics", 46);`
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>
CodePudding user response:
Use Dynamic Query. Form the query dynamically for each table and use string_agg()
to concatenate it and execute the query using sp_executesql
declare @tables varchar(max),
@tenantid int,
@sql nvarchar(max)
select @tables = 'Employee,Student,Teacher',
@tenantid = 64;
select @sql = string_agg('select [TableName] = ''' value ''', [Count] = count(*) from ' quotename(value) ' where tenantid = @tenantid', ' union all' char(13) )
from string_split(@tables, ',')
print @sql
exec sp_executesql @sql, N'@tenantid int', @tenantid
CodePudding user response:
Use UNION ALL:
SELECT 'Employee' AS "TableName", COUNT(*) AS "Count" FROM Employee WHERE tenantid = 64
UNION ALL
SELECT 'Student' AS "TableName", COUNT(*) AS "Count" FROM Student WHERE tenantid = 64
UNION ALL
SELECT 'Teacher' AS "TableName", COUNT(*) AS "Count" FROM Teacher WHERE tenantid = 64
View example (I'm not sure about efficiency):
CREATE VIEW some_counters_view AS
SELECT 'Employee' AS "TableName", tenantid FROM Employee
UNION ALL
SELECT 'Student' AS "TableName", tenantid FROM Student
UNION ALL
SELECT 'Teacher' AS "TableName", tenantid FROM Teacher
;
SELECT "TableName", COUNT(*) AS "Count"
FROM some_counters_view
WHERE tenantid = 64
GROUP BY "TableName"