我有一个示例查询,如下所示:
SELECT *
FROM [#temp1]
UNION
SELECT *
FROM [#temp2]
UNION
SELECT *
FROM [#temp3]
UNION
SELECT *
FROM [#temp4]
UNION
SELECT *
FROM [#temp5]
如何将这些查询请求移动到新表中? 注意:我的SQL版本是:
Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.0 <X64> (Build 6002: Service Pack 2)
我尝试了另一个我发现的Stackoverflow答案,即
CREATE TABLE managers AS SELECT * FROM employees WHERE desg = 'MANAGER';
但我收到错误:Incorrect syntax near the keyword 'as'.
这是我的完整查询因上述错误而失败:
CREATE TABLE #temp_UNION as
SELECT *
FROM [#temp1]
UNION
SELECT *
FROM [#temp2]
UNION
SELECT *
FROM [#temp3]
UNION
SELECT *
FROM [#temp4]
UNION
SELECT *
FROM [#temp5]
有关我如何搞砸的任何建议吗?
谢谢你, 射线
答案 0 :(得分:20)
在SQL Server中,您必须使用
SELECT <COLUMNS_LIST>
INTO <NEW_TABLE_NAME>
FROM <TABLES, WHERE ETC>
更多信息@ http://msdn.microsoft.com/en-us/library/ms188029.aspx
试试这个:
SELECT *
INTO #temp_UNION
FROM
(
SELECT *
FROM [#temp1]
UNION
SELECT *
FROM [#temp2]
UNION
SELECT *
FROM [#temp3]
UNION
SELECT *
FROM [#temp4]
UNION
SELECT *
FROM [#temp5]
) a
答案 1 :(得分:1)
insert into temp_UNION
select * from (
SELECT *
FROM [#temp1]
UNION
SELECT *
FROM [#temp2]
UNION
SELECT *
FROM [#temp3]
UNION
SELECT *
FROM [#temp4]
UNION
SELECT *
FROM [#temp5]
)
答案 2 :(得分:0)
或者您不需要使用派生表。你也可以这样做
SELECT * INTO #temp_UNION
FROM [#temp1]
UNION
SELECT * FROM [#temp2]
UNION SELECT * FROM [#temp3]
UNION SELECT * FROM [#temp4]
UNION SELECT * FROM [#temp5]