开发者

How to move UNION query results to a new table?

I have a sample query as shown below:

SELECT     *
FROM         [#temp1]
UNION
SELECT     *
FROM         [#temp2]
UNION
SELECT     *
FROM         [#temp3]
UNION
SELECT     *
FROM         [#temp4]
UNION
SELECT     *
FROM         [#temp5]

How do I move this request of these queries into a new table? Note: My verison of SQL is:

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) 

I tried another Stackoverflow answer I found, i.e.

CREATE 开发者_Python百科TABLE managers AS SELECT * FROM employees WHERE desg = 'MANAGER';

But I get an error of : Incorrect syntax near the keyword 'as'.

Here was my full query that failed with the above error:

CREATE TABLE #temp_UNION as


SELECT     *
FROM         [#temp1]
UNION
SELECT     *
FROM         [#temp2]
UNION
SELECT     *
FROM         [#temp3]
UNION
SELECT     *
FROM         [#temp4]
UNION
SELECT     *
FROM         [#temp5]

Any suggestions please on how I'm goofing up?

Thank you, Ray


In SQL Server you have to use

SELECT <COLUMNS_LIST>
  INTO <NEW_TABLE_NAME>
  FROM <TABLES, WHERE ETC>

More information @ http://msdn.microsoft.com/en-us/library/ms188029.aspx

Try this:

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


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


or you dont need to use derived table. You can do this too

SELECT *   INTO  #temp_UNION  
FROM         [#temp1]     
UNION     
SELECT     *     FROM         [#temp2]     
UNION     SELECT     *     FROM         [#temp3]     
UNION     SELECT     *     FROM         [#temp4]     
UNION     SELECT     *     FROM         [#temp5] 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜