如何从查询中删除#temp表

时间:2013-04-15 12:20:06

标签: sql

我有三个查询将数据放在各自的#temp表中。稍后,在一个查询中,再次使用#temp表来获取数据。

select {some columns} into #temp1 from {some tables} where {conditions1}
select {some other columns} into #temp2 from {some tables} where {conditions2}
select {some other columns} into #temp3 from {some tables} where {conditions3}

select {some columns from all #temp tables} from #temp1, #temp2, #temp3 where {conditions}

我想摆脱这些#temp表,并希望在没有那些#temp表的情况下运行最后一个查询。

任何想法!!!

如何编写三个不同的函数并将所有三个查询放在这些函数中并从第三个查询中调用函数!!

由于

1 个答案:

答案 0 :(得分:2)

如果您使用的是MSSql,请使用CTE

;with cte1 as (
    select {some columns} from {some tables} where {conditions1}
), 
cte2 as (
    select {some other columns} from {some tables} where {conditions2}
),
cte3 as (
    select {some other columns} from {some tables} where {conditions3}
)
select {some columns from all ctes} from cte1, cte2, cte3 where {conditions}

这应该运行得更快,因为不需要将数据插入临时表。

避免临时表的另一个好处是,使用临时表有时会对性能产生很大影响,因为整个sql server只有一个tempdb而且大量使用tempdb,可能会阻塞其他查询。只是谷歌临时表和性能影响,你会发现很多关于这个主题的文章