The rise of TOP, and fall of ROWCOUNT


In SQL Server 2005, TOP has gained a few new capabilities.

SELECT TOP (scalar expression | variable | subquery) [PERCENT] *
FROM    aTable

TOP can also be used in DML statements. Previously you may have used ROWCOUNT to limit the affected data, but apparently from Katmai (next version of SQL Server) ROWCOUNT will have no affect on DML statements! So, if you are currently using ROWCOUNT to throttle DML statements, I recommend you move over to the TOP operator. It’s cleaner and has better support going forward….

The old way
SET ROWCOUNT 1000;
WHILE 1 = 1
BEGIN
    DELETE FROM aTable
    WHERE KeyId < 5000000;
    IF @@rowcount < 1000 BREAK;
END
SET ROWCOUNT 0;

The new way
WHILE 1 = 1
BEGIN
    DELETE TOP(1000) FROM aTable
    WHERE KeyId < 5000000;
    IF @@rowcount < 1000 BREAK;
END

After running a few tests, I believe that the performance of the TOP operator might by slightly slower than ROWCOUNT. I’ll do some further analysis and post it up here at a later date…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s