• I don't like the script, and I like the advice to use WHILE instead of CURSOR even less.

    My take on this:

    1. Set-based is (almost) always faster than iterative. Avoid both WHILE and CURSOR whenever you can.

    2. If you do have to use looping, then use the best tool for the job. And that is *not* a WHILE loop. A cursor outperforms a WHILE loop - when used appropriately. Which means that you have to supply some options, because the default options suck.

    The comment in the article on forgetting to DEALLOCATE is similar to saying not to use WHILE loops because sometimes people forget to add the SET @i += 1 or whatever else is used to move to the next, and then you get an infinite loop. Those are programming errors that will be caught during peer review and testing.

    Sources:

    Performance of cursor with standard options versus "good" options: http://sqlblog.com/blogs/hugo_kornelis/archive/2007/11/21/curious-cursor-optimization-options.aspx

    Performance of cursor vs while loop: http://sqlblog.com/blogs/hugo_kornelis/archive/2007/11/28/poor-men-see-sharp-ndash-more-cursor-optimization.aspx

    The specific script in the article is unreliable as a replacement for a cursor. It depends on a column with incrementing values being present in the query results, which is not always the case. The example given relies on sys.servers containing only a row for the current server with server_id equal to 0, and all other rows containing linked servers and having server_id numbered consecutively and ascending. If you have for instance three linked servers and then delete the first, will the others be renumbered, or will you simply have rows for servier_id 0 (not linked), and 2 and 3 (linked)? In the latter case, you will get incorrect results from the WHILE example, but the cursor will still work.

    This can be "fixed" by first storing the results of the query in a temporary table with an additional IDENTITY column, but that adds more statements to the code (defying the "short code" argument of the author) and slows down performance.


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/