2013-06-20 62 views
4

我必須做的一個UNION stament這樣或多或少:如何在SQL Server中得到「選擇」語句中的表名

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

UNION 

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

檢索到的數據將是僱員或EMPLOYEES_HISTORY但不是在兩個表。

我需要知道數據來自哪個表。

回答

8
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] 

我用UNION ALL而不是UNION一樣會有兩個分支沒有重複。所以它可以避免一些不必要的工作在整個結果集中刪除重複項。

如果有可能的分支(ES)內重複添加DISTINCT個別SELECT(S)

1

您可以附加一個新的領域,如下圖所示:

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

UNION 

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

你也可以使用一個alias正如馬丁在答案中所表明的那樣。

0

你不能做這樣的事情:

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] 
0

可以實現Using Table Aliases

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] 
+3

你的回答實際上並未使用任何表的別名。 –