我可以在SQL查询的结果中包含表名吗?

时间:2009-10-08 12:59:15

标签: sql

如果我有两张桌子:

Actor:
ID | Name
1  : Patrick
3  : Emma
7  : Vanessa

Singer:
ID | Name
4  : Will
5  : Madonna
13 : Emma

我可以从SQL查询生成下表吗,其中包含每条记录来自的表名?

ID | Career | Name
1  : Actor  : Patrick
3  : Actor  : Emma
4  : Singer : Will
5  : Singer : Madonna
7  : Actor  : Emma
13 : Singer : Emma

我假设ID列项在两个表中是唯一的,但不是名称。

6 个答案:

答案 0 :(得分:14)

select ID, 'Actor' as Career, Name from Actor
union all
select ID, 'Singer' as Career, Name from Singer

或者沿着这些方向发展。

答案 1 :(得分:4)

SELECT ID, 'Actor' AS Career, Name FROM Actor
UNION
SELECT ID, 'Singer' AS Career, Name FROM Singer

答案 2 :(得分:4)

好的,有两个人打我到我发布的示例查询。

但是,我认为对你的根问题更好的答案是,如果“职业”是你数据中的一个相关属性,并且这些ID是唯一的,为什么不能有一个表,其中Career是一个实际的列?

答案 3 :(得分:2)

由于您知道要从查询的表名,因此您只需将表名作为文字值包含在结果集中:

SELECT ID, 'Actor', Name FROM Actor
  UNION SELECT ID, 'Singer', Name FROM Singer;

答案 4 :(得分:2)

尝试:

select id, 'Actor' as Career, Name
from Actor
union
select id, 'Singer' as Career, Name
from Singer

答案 5 :(得分:0)

这也不理想,但它确实回答了你的问题,假设数据库只有两个表。

DECLARE @t1 nvarchar(10) = (SELECT top 1 TABLE_NAME
                            FROM INFORMATION_SCHEMA.TABLES)
DECLARE @t2 nvarchar(10) = (SELECT top 1 TABLE_NAME
                            FROM INFORMATION_SCHEMA.TABLES
                            WHERE NOT TABLE_NAME = @t1)

DECLARE @SQLcommand nvarchar(400)

SET @SQLcommand = 'select ID, '+ @t1 +' as Career, Name from ' + @t1 +
                  ' union all select ID, '+ @t2 +' as Career, Name from ' +@t2

EXEC(@SQLcommand)

我同意上面的说法,设计确实需要考虑你需要这个。