表記錄的插入方式有兩種。其一,先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的辦法,把所有的語句都拼接好。好處是性能比方法二好,但缺點也很明顯,可讀性不強;
方法四:其實,不同的功能,還是最好分成不同的存儲過程,優化,維護都更簡單。
不知道有沒有更好的方式?
??
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
