如何使用union运算符创建临时表
select top 5 Name into [#Production.Productmodel]
from [Production].[ProductModel]
select top 5 Name into [#purchasing.shipmethod]
from [Purchasing].[ShipMethod]
select Name into #productionprod
select Name from [#purchasing.shipmethod]
union
select Name from [#Production.Productmodel]
但我仍然收到错误(列名无效)
答案 0 :(得分:3)
您的查询失败的原因是您在查询中重复SELECT NAME
,因此删除第二个:
select Name
into #productionprod
from [#purchasing.shipmethod]
union
select Name from [#Production.Productmodel]
你也可以使用两个这样的子查询:
select Name into #productionprod
from (
select Name from [#purchasing.shipmethod]
union
select Name from [#Production.Productmodel]
) subquery
旁注:如果您首先选择[#Production.Productmodel]
和[#purchasing.shipmethod]
的唯一原因是将这些临时表用作SELECT ... INTO #productionprod
的来源,那么您的查询可以简化为这样:
SELECT Name INTO #productionprod
FROM (
SELECT TOP 5 Name
FROM [Production].[ProductModel] ORDER BY name
UNION
SELECT TOP 5 Name
FROM [Production].[ShipMethod] ORDER BY name
) a
请注意,当您使用TOP n
而ORDER BY
时,订单未定义,如documentation中所述:
当TOP与ORDER BY子句一起使用时,结果 set仅限于前N个有序行数;否则,它 以未定义的顺序返回前N行。
答案 1 :(得分:0)
您可以使用into
。这是一个例子:
select Name
into #productionprod
from [#purchasing.shipmethod]
union
select Name
from [#Production.Productmodel]