表記錄的插入方式有兩種。其一,先create table 再 insert into from ...。其二, 直接 select into。
第一種方式,由於要記錄日誌,因此IO消耗更多,duration 更長。一般來說能用 select into 的,就儘量不要用 insert into的方式。
有時,存儲過程中會需要,根據不同的條件,從不同的表中獲取數據放入一個臨時表。看起來,這樣就需要在不同的分支語句中,寫多個對同一張的 select into 語句。
例如:
if (@b=1)
begin
select a.id, a.name, b.price
into #temp
from A inner join B on (a.id=b.id)
end else if (@b=2)
begin
select d.id, d.name, c.price
into #temp
from D inner join C on (d.id=c.id)
end
但創建存儲過程時會報錯,說 #temp 表已經存在。
怎麼解決呢?
方法一:用第一種方式,問題是性能差;
方法二:偷懶一些,但性能更好的方法
select a.id, a.name, b.price
into #tempA
from A inner join B on (@b=1 and a.id=b.id)
where @b=1
select d.id, d.name, c.price
into #tempB
from D inner join C on (@b=2 and d.id=c.id)
where @b=2
select *
into #temp
from ( select * from #tempA union all select * from #tempB )
方法三:用動態sql的辦法,把所有的語句都拼接好。好處是性能比方法二好,但缺點也很明顯,可讀性不強;
方法四:其實,不同的功能,還是最好分成不同的存儲過程,優化,維護都更簡單。
不知道有沒有更好的方式?