close
T-SQL找最大值方法的效能比較
引用內容:
KB-T-SQL找最大值方法的效能比較
今天跟同事討論用T-SQL查資料表中最大值的方法,一群人總共想出三種: SELECT TOP 1 + ORDER BY, SELECT MAX, 再來是用CURSOR的FETCH LAST。三種做法,哪一個最有效率呢? 初步想起來,用CURSOR是最笨重的,肯定最慢。剩下的兩種,MAX()是Aggregate Function,依據我過去寫SQLCLR自訂Aggregate Function的經驗,每一列的資料都要送入Funtion中比較,應該會輸給內建的ORDER BY吧?
找來一個有150萬筆資料的Table,做了以下的實驗:
--方法1 用ORDER BY+TOPselect top 1 dst from netlog order by dst desc
--方法2 用MAX
select max(dst) from netlog
--方法3 用CURSOR
declare @dst varchar(15)
declare cur scroll cursor for select dst from netlog order by dst
open cur
fetch last from cur into @dst
select @dst
close cur
deallocate cur
全站熱搜