在MSSQL 中 適當使用暫存表對於效能調教有很大的幫助
有幾種Create Table方式
@[TableName]
# [TableName]
## [TableName]
差別在哪裡呢? 讓我們繼續看下去
第一種是#temp
#Temp table 只能在自己的Session Scope
使用
如果要跨Session Scope使用資料表 只能使用實體表或##TempTable

他是使用tempdb及具實體IO且因為他是存在資料庫中記得用完後要DROP掉
--#的Temp Talale
CREATE TABLE #temp1
(
ID BIGINT,
[NAME] NVARCHAR(20)
)
INSERT INTO #temp1 (ID,[NAME])
SELECT ID,[NAME]
FROM Employee
drop table #temp1
第二種是##temp
##的TempTable慎用!! 因為它是屬實全域的TempTable(整個資料庫都看的到)
可以跨Session Scope
CREATE TABLE ##temp1
(
ID BIGINT,
[NAME] NVARCHAR(20)
)
drop table ##temp1
第三種是@temp
將TABLE
當作是一個變數來使用,它也是使用tempdb及具實體IO且因為他是存在資料庫中,但最後它會自己Drop
掉
--@的Temp Table
DECLARE @temp1 AS TABLE
(
ID BIGINT,
[NAME] NVARCHAR(20)
)
SELECT *
FROM @temp1
WAITFOR DELAY '00:00:15'
我寫一個範例建立一個@temp1
資料表之後Delay 15 秒,之後馬上在TempDB
查詢暫存資料表可以查到有一個temp資料表(就是@temp1
)

15秒過後資料表會自己Drop

那有人會詢問說@temp和#temp差在哪邊?
這是一個好問題!!
他們有兩個差異
@temp
會自己Drop table,#temp
不會@temp
沒有統計值,#temp
有統計值
介紹可參考我的另一篇 影響Query Optimizer產生執行計畫的關鍵(統計值)
如果本文對您幫助很大,可街口支付斗內鼓勵石頭^^
