SQL server Temp table with joins inside other select

SQL server Temp table with joins inside other select

我有以下结构:

Create @temp
Select ...inser...into @temp where ...

(select ... from @temp
Join tblA where ... )
UNION
(Select ... from @temp
join tblB where ... )

在上面构建之后 table 我需要能够执行 WHERE, JOINS, ...

类似于:

Select ... from (above statement)
join ....
where....

我不知道如果 @temp、joins、union... 可以在其他 select 中。

或者我唯一能做的就是创建一个带有第一个语句结果的 @Temp2 插入,然后与其他连接一起工作,其中...?

更新 1:

我也在尝试:

With cte (query returned columns)
as
(same query I was using to build my @temp as before)

(select ... from cte
join tblA
where...)
UNION
(select ... from cte
join tblB
where...)

但我在如何执行其他连接时卡在了同一点上,其中...总结果以上

Create @temp
Select ...inser...into @temp where ...

;with temp2 as
(
    select ... from @temp Join tblA where ...
    UNION
    Select ... from @temp join tblB where ... 
)
select ... from temp2
join ....
where....

其实不用临时也可以-table:

WITH myCTE [ ( column_name [,...n] ) ]
AS
( here you define your query )

然后您只需执行 Select 但使用 CTE

Select ... from myCTE
join ....
where....

关于 CTE 你可以阅读 Here 更新后

Select fields from myCTE join table1
Union
Select fields from myCTE join table2

查询中没有括号