Sql Server, Temporary Tables With Truncate Vs Table Variable With Delete
Solution 1:
Running the followign to scripts, it would seem that the Table Variable is the better option
CREATETABLE #Temp(
ID INT
)
DECLARE@IntINT,
@InnerIntINTSELECT@Int=1,
@InnerInt=1
WHILE @Int<50000BEGIN
WHILE @InnerInt<10BEGININSERTINTO #Temp SELECT@InnerIntSET@InnerInt=@InnerInt+1ENDSELECT@Int=@Int+1,
@InnerInt=1TRUNCATETABLE #Temp
ENDDROPTABLE #TEMP
GO
DECLARE@TempTABLE(
ID INT
)
DECLARE@IntINT,
@InnerIntINTSELECT@Int=1,
@InnerInt=1
WHILE @Int<50000BEGIN
WHILE @InnerInt<10BEGININSERTINTO@TempSELECT@InnerIntSET@InnerInt=@InnerInt+1ENDSELECT@Int=@Int+1,
@InnerInt=1DELETEFROM@TempENDFrom Sql Profiler
CPU Reads Writes Duration
363752799937039319
vs
CPU Reads Writes Duration
147501700031217376Solution 2:
Quite frankly, with only 10 or 20 (or even 100) entries, any difference in speed would be in a sub-nanosecond realm. Forget about it - don't even waste a second of your brain time on this - it's a non-issue!
In general
table variables will be kept in memory up a certain size - if they go beyond that, they're swapped out to disk in the
tempdbdatabase, too - just like temporary tables. Plus: if a temporary table has only a handful of entries, they'll most like be stored on a single 8k page anyway, and as soon as you access one of the entries, that entire page (and thus the whole temporary table) will be in SQL Server memory - so even here, there's really not a whole lot of benefits to table variables...table variables don't support indices nor statistics, which means if you have more than a handful of entries, and especially if you need to search and query this "entity", you're better off with a temporary table
So all in all : I personally use temporary tables more often than table variables, especially if I have more than 10 entries or something like that. Being able to index the temp table, and having statistics on it, usually pays off big time compared to any potential gain a table variable might have, performance-wise.
Post a Comment for "Sql Server, Temporary Tables With Truncate Vs Table Variable With Delete"