首页 > 解决方案 > 联合查询结果到临时表

问题描述

我有一个要插入临时表的子查询。但是,我收到语法错误,例如SQL Error [102] [S0001]: Incorrect syntax near ')'..

select *
into #TempTable
from (
        SELECT x,y,z
        FROM 
         schemaA.tableC
        where (x  = '1234')
        UNION 
        SELECT x,y,z
        FROM 
         schemaB.tableC
        where (x  = '1234')
)

select *
from #TempTable

标签: sql-server

解决方案


您需要为内部查询提供别名:

select *
into #TempTable
from (
        SELECT x,y,z
        FROM 
         schemaA.tableC
        where (x  = '1234')
        UNION 
        SELECT x,y,z
        FROM 
         schemaB.tableC
        where (x  = '1234')
) AS P

select *
from #TempTable

简单来说,结构是:

SELECT
    *
FROM
   (SELECT * FROM MyTable) AS P

推荐阅读