• Jeff Moden - Wednesday, June 28, 2017 6:55 AM

    Brandie Tarvin - Wednesday, June 28, 2017 4:51 AM

    jonathan.crawford - Tuesday, June 27, 2017 9:01 AM

    Jeff Moden - Monday, June 26, 2017 6:44 PM

    Eric M Russell - Saturday, June 24, 2017 8:24 PM

    So, did anyone else have a strangely intense dream recently about being, outside looking up at the night sky, and then a constellation of stars coalesce into a UFO that lands nearby?

    Crud.  Sorry.  Didn't mean for you to see me.

    Great. Jeff's moved on from pork chop launchers to "nuke it from orbit". Nobody write any cursors!

    HA! I defy your directive and write one anyway!

    (Cursors do have their place, ya know).

    Heh...  what's the last cursor you wrote and what did it do?

    Every tool in SQL Server has its use cases; there are no bad tools. Well, except auto-shrink.

    I wrote two cursors in the last year, both for the same subsystem. This subsystem reads files with products, stock and pricing from various vendors and stores the data in two tables: headers (one per file) and lines (one per line). Files can be as small as a few dozen lines, or as big as 100K lines, Some files are imported daily, others up to 24x per day.

    Cursor 1: Iterates over the headers. For each header, determine the type of purging allowed (there are three versions), delete lines that can be purged, then update the linecount in the header. The deletion could easily have been done in a single set-based query (well, three queries), but the amount of rows affected would bloat the log so I'd have to add chunking. And then the update of the headers to set the correct linecount would become much more complex. The cursor makes the code easier, gives me chunking for free, and it performs in less then 1% of the available maintenance window.

    Cursor 2:  Because all searches in the imported data are based on substrings (LIKE '%' + @Search + '%'), they are slow. So we cache search results. If the same search string is reused, we simply get the results from a cache table. After business hours, a process starts that uses a cursor to loop over search strings (in order of relevance, based on how often and how long ago the search string was used) and refreshes the search results based on the then current data. Half an hour before start of business the process aborts and any remaining cached search results are thrown out to prevent serving outdated results. The cursor here gives me a very easy way to interrupt the process when it runs out of time, and to ensure that the most relevant search terms are refreshed first.


    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/