Select 进入#TempTable

Select into #TempTable

我有类似下面的场景

Select x, y, z
from mytable
where x = 1

UNION

Select x, y, z
from mytable2
where x = 1

我想将结果放入#TempTable,然后将结果创建一个数据透视表放入#TempTable2

我试过了

SELECT * INTO #TempTable FROM (
Select x, y, z
from mytable
where x = 1

UNION

Select x, y, z
from mytable2
where x = 1
)

但它在 ')' 附近出现语法错误 我忘记了我所做的所有其他变体,但 none 其中的变体有效

为派生的 table 添加一个别名。这里我用X是因为我想象力丰富

SELECT * 
INTO #TempTable 
FROM 
   (
   Select x, y, z
   from mytable
   where x = 1
   UNION
   Select x, y, z
   from mytable2
   where x = 1
   ) AS X

SQL 服务器需要 FROM 子句中对象的引用。无别名 = 无参考
如果我们使用 CTE

重写查询,您可以看到这一点
WITH myUnion AS
   (
   Select x, y, z
   from mytable
   where x = 1
   UNION
   Select x, y, z
   from mytable2
   where x = 1
  )
SELECT * 
INTO #TempTable 
FROM myUnion