【问题标题】:How can I get table name as column from the current table in SQL Server如何从 SQL Server 中的当前表中获取表名作为列
【发布时间】:2016-06-22 21:39:12
【问题描述】:

我正在尝试找到一种方法从 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 语句的第一列中硬编码表名,这没有多大意义,有没有办法动态获取第一列中的表名?

欣赏你的想法!

说唱

【问题讨论】:

  • 我认为您当前的方法没有任何问题——认为没有更好的解决方案。

标签: sql tsql sql-server-2012


【解决方案1】:

您如何看待将表名作为变量传递?
看一个这个简单的例子(我没有尝试运行它)。

    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

【讨论】:

    【解决方案2】:

    这将显示您数据库中所有表中的所有字段名称。

    USE your_DB
    GO
    SELECT t.name AS table_name,
    SCHEMA_NAME(schema_id) AS schema_name,
    c.name AS column_name
    FROM sys.tables AS t
    INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
    WHERE c.name LIKE '%ticker%'
    ORDER BY schema_name, table_name;
    

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多