sql - 如何从 SQL Server 中的当前表中获取表名作为列

标签 sql tsql sql-server-2012

我正在尝试找到一种方法从 SQL Server 2012 中的当前表中获取“表名”作为列

SELECT 
    'School1.dbo.Person', Age, COUNT(Age) 
FROM 
    School1.dbo.Person
GROUP BY 
    Age

UNION ALL

SELECT 
    'School2.dbo.Person', Age, COUNT(Age) 
FROM 
    School2.dbo.Person
GROUP BY 
    Age

由于我在每个 select 语句的第一列中对表名进行硬编码,这没有多大意义,有没有办法动态获取第一列中的表名?

欣赏你的想法!

说唱

最佳答案

您如何看待将表名作为变量传递?
看看这个快速示例(我没有尝试运行它)。

    declare @tableName1 varchar(max) = 'School1.dbo.Person';
    declare @tableName2 varchar(max) = 'School2.dbo.Person';

    declare @sql1 nvarchar(max) = N'SELECT ''' + @tableName1 + ''', Age, COUNT(Age) FROM ' + @tableName1 + ' GROUP BY Age';
    declare @sql2 nvarchar(max) = N'SELECT ''' + @tableName2 + ''', Age, COUNT(Age) FROM ' + @tableName2 + ' GROUP BY Age';

    declare @table1 as table(tabName varchar(max), Age int, AgeCount int);
    declare @table2 as table(tabName varchar(max), Age int, AgeCount int);

    insert into @table1 execute sp_executesql @sql1;
    insert into @table2 execute sp_executesql @sql2;

    select * from @table1
    union all
    select * from @table2

关于sql - 如何从 SQL Server 中的当前表中获取表名作为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37978726/

相关文章:

sql - 如何在一个 LIKE 模式中描述以一个或两个数字结尾的字符串?

sql - 获取 group by 语句 sqlite 中每个组的 id 列表

sql-server - 具有挑战性的递归 T-SQL 查询

sql - 使用SQL Server 2012将多行插入到临时表中

sql-server - 如何从 SSDT 发布脚本中删除 ALTER DATABASE 语句?

sql-server - 兼容模式允许新命令?

mysql - SQL-获取平均计数 GROUP BY 月

mysql - 在数据库中存储喜欢和不喜欢

sql - 从路径中删除文件名

sql-server - 区分大小写变得疯狂