简体   繁体   中英

How can I get table name as column from the current table in SQL Server

I'm trying to find a way to get the "table name" as column from the current table in 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

As I'm hard-coding the table name in first column of each select statement, it doesn't make much sense, is there way I could get the table name in first column dynamically?

Appreciate your thoughts!

RAP

What do you think about passing table names as variables?
Look a this quick example (I didn't try to run it).

    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

This will show you all your field names in all your tables in your database.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM