如何在SQL Server中的“select”语句中获取表名

如何在SQL Server中的“select”语句中获取表名,sql,sql-server,tsql,Sql,Sql Server,Tsql,我或多或少得做出这样的联合声明: select [table_name], name, address from Employees where [my_condition] UNION select [table_name], name, address from Employees_history where [my_condition] 检索到的数据将在Employees或Employees_历史记录中,但不在这两个表中 我需要知道数据来自哪个表 SELECT 'Employees'

我或多或少得做出这样的联合声明:

select [table_name], name, address
from Employees
where [my_condition]

UNION

select [table_name], name, address
from Employees_history
where [my_condition]
检索到的数据将在Employees或Employees_历史记录中,但不在这两个表中

我需要知道数据来自哪个表

SELECT 'Employees' AS [table_name],
       name,
       address
FROM   Employees
WHERE  [my_condition]
UNION ALL
SELECT 'Employees_history' AS [table_name],
       name,
       address
FROM   Employees_history
WHERE  [my_condition] 
我使用UNIONALL而不是UNION,因为两个分支之间不会有重复项。因此,它可以避免在整个结果集中删除重复项的一些不必要的工作


如果分支中可能存在重复项,请向单个选项添加DISTINCT,您可以添加一个新字段,如下所示:

select [table_name], name, address, 'Employees'
from Employees
where [my_condition]

UNION

select [table_name], name, address, 'History'
from Employees_history
where [my_condition]

您也可以使用一个别名,正如Martin在回答中所示

您不能执行以下操作:

select 'Employees' as table_name, name, address
from Employees
where [my_condition]

UNION

select 'Employees_history' as table_name, name, address
from Employees_history
where [my_condition]
这是可以实现的


您的答案实际上没有使用任何表别名。
SELECT 'Employees' AS [table_name],
       name,
       address
FROM   Employees
WHERE  [my_condition]

UNION

SELECT 'History' AS [table_name],
       name,
       address
FROM   Employees_history
WHERE  [my_condition]