<PRE lang=sql>CREATEtable #T (s varchar(128)) DECLARE@Ttable (s varchar(128)) INSERTinto #T select'old value #' INSERTinto@Tselect'old value @' BEGINtransaction UPDATE #T set s='new value #' UPDATE@Tset s='new value @' ROLLBACKtransaction SELECT*from #T SELECT*from@T s --------------- old value # s --------------- new value @</PRE>
CREATEtable NUM (n intprimarykey, s varchar(128)) GO SET nocount on DECLARE@nint SET@n=1000000 WHILE@n>0begin INSERTinto NUM SELECT@n,'Value: '+convert(varchar,@n) SET@n=@n-1 END GO
然后创建存储过程:T1
CREATEprocedure T1 @totalint AS CREATEtable #T (n int, s varchar(128)) INSERTinto #T select n,s from NUM WHERE n%100>0and n<=@total DECLARE@resvarchar(128) SELECT@res=max(s) from NUM WHERE n<=@totaland NOTexists(select*from #T WHERE #T.n=NUM.n) GO
CREATEprocedure T2 @totalint AS CREATEtable #T (n intprimarykey, s varchar(128)) INSERTinto #T select n,s from NUM WHERE n%100>0and n<=@total DECLARE@resvarchar(128) SELECT@res=max(s) from NUM WHERE n<=@totaland NOTexists(select*from #T WHERE #T.n=NUM.n) GO
在下面的对比中你可以发现已经大大的提速了.
然后再来一次提速:给它加个聚集索引
CREATEprocedure T3 @totalint AS CREATEtable #T (n int, s varchar(128)) INSERTinto #T select n,s from NUM WHERE n%100>0and n<=@total CREATEclusteredindex Tind on #T (n) DECLARE@resvarchar(128) SELECT@res=max(s) from NUM WHERE n<=@totaland NOTexists(select*from #T WHERE #T.n=NUM.n) GO
很惊讶速度已经提高了很多!
那好了,咱们再来测试一下table变量的速度吧
CREARE procedure V1 @totalint AS DECLARE@Vtable (n int, s varchar(128)) INSERTinto@Vselect n,s from NUM WHERE n%100>0and n<=@total DECLARE@resvarchar(128) SELECT@res=max(s) from NUM WHERE n<=@totaland NOTexists(select*from@V V WHERE V.n=NUM.n) GO
然后再来创建一个有主键的:
CREATEprocedure V2 @totalint AS DECLARE@Vtable (n intprimarykey, s varchar(128)) INSERTinto@Vselect n,s from NUM WHERE n%100>0and n<=@total DECLARE@resvarchar(128) SELECT@res=max(s) from NUM WHERE n<=@totaland NOTexists(select*from@V V WHEREre V.n=NUM.n) GO<
然后咱们来看看我测试的结果吧!
Table 1, using SQL Server 2000, time in ms
Records
T1
T2
T3
V1
V2
10
0.7
1
13.5
0.6
0.8
100
1.2
1.7
14.2
1.2
1.3
1000
7.1
5.5
27
7
5.3
10000
72
57
82
71
48
100000
883
480
580
840
510
1000000
45056
6090
15220
20240
12010
But the real shock is when you try the same on SQL Server 2005: