SQL从每个表逐条获取行数



我正在开发一个多租户应用程序。大多数表包含一个列tenant_id。我想知道特定tenant_id在所有表中的行数。

,表:-

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);`

获取tenantid = 64的每个表的行数的示例结果

tbody> <<tr>学生老师
TableNameCount
员工2
3
1

使用动态查询。动态地为每个表生成查询,并使用string_agg()将其连接起来,然后使用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

,db&lt的在小提琴演示

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

查看示例(我不确定效率):

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"

相关内容

  • 没有找到相关文章

最新更新