Monday, October 26, 2009

INSERT's inside transactions

Are you a geek? Then read on. :-)

Reading Inside SQL Server 2005: Query Tunning and Optimization, I stumbled upon this beaultiful code sample. The guy (yes, a guy - it seems Ms. Delaney is subcontracting for some chapters...) creates a big sample table with 250,000 rows on it.

And there's not a single shred of comment about the code. He's doing 250,000 INSERT's on a table. In order to optimize it, he opens a transaction right before the loop starts, and on every 1,000 INSERT's he does a COMMIT then opens another transaction. This prevents SQL Server from opening a transaction on each INSERT. (Yes, Luke. When a data modification command to SQL Server you send, a transaction it automatically opens if the command is not already inside one. This allows you, for example, to change your mind and issue a ROLLBACK inside a trigger - even without a preceding BEGIN TRAN).

By using the explicit transactions around the INSERT's, the code runs them on 250 transactions, instead of 250 thousand ones. As I've said before, beaultiful. Simply beaultiful.

And in case you didn't notice: yes, I'm a geek. :-)

No comments:

Post a Comment