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

时间:2016-06-22 21:39:12

标签: 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语句的第一列中对表名进行硬编码,它没有多大意义,是否可以动态地在第一列中获取表名?

欣赏你的想法!

RAP

2 个答案:

答案 0 :(得分:0)

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

    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

答案 1 :(得分:0)

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

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;