我正在尝试找到一种方法从 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/

10-16 14:19