簡體   English   中英

如何從查詢中刪除#temp表

[英]How to get rid of #temp tables from the query

我有三個查詢,分別將數據放在各自的#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表的情況下運行最后一個查詢。

任何想法!!!

如何編寫三個不同的函數並將所有三個查詢放入這些函數中,然后從第三個查詢中調用函數!!

謝謝

賈伊

如果您使用的是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服務器只有一個tempdb,而大量使用tempdb則可能會阻塞其他查詢。 只是google臨時表和性能影響,您會發現很多關於該主題的文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM