<p>I knew of some performance reasons back in the SQL 7 days, but do the same issues still exist in SQL Server 2005? If I have a resultset in a stored procedure that I want to act upon individually, are cursors still a bad choice? If so, why?</p>

[{'answer_id': 58149, 'author': 'rpetrich', 'author_id': 4007, 'author_profile': 'https://Stackoverflow.com/users/4007', 'pm_score': 4, 'selected': False, 'text': '<p>I think cursors get a bad name because SQL newbies discover them and think "Hey a for loop! I know how to use those!" and then they continue to use them for everything.</p>\n\n<p>If you use them for what they\'re designed for, I can\'t find fault with that.</p>\n'}, {'answer_id': 58152, 'author': 'Michael Haren', 'author_id': 29, 'author_profile': 'https://Stackoverflow.com/users/29', 'pm_score': 3, 'selected': False, 'text': "<p>SQL is a set based language--that's what it does best.</p>\n\n<p>I think cursors are still a bad choice unless you understand enough about them to justify their use in limited circumstances.</p>\n\n<p>Another reason I don't like cursors is clarity. The cursor block is so ugly that it's difficult to use in a clear and effective way.</p>\n\n<p>All that having been said, there <em>are</em> some cases where a cursor really is best--they just aren't usually the cases that beginners want to use them for.</p>\n"}, {'answer_id': 58153, 'author': 'Guy Starbuck', 'author_id': 2194, 'author_profile': 'https://Stackoverflow.com/users/2194', 'pm_score': 1, 'selected': False, 'text': '<p>The basic issue, I think, is that databases are designed and tuned for set-based operations -- selects, updates, and deletes of large amounts of data in a single quick step based on relations in the data.</p>\n\n<p>In-memory software, on the other hand, is designed for individual operations, so looping over a set of data and potentially performing different operations on each item serially is what it is best at.</p>\n\n<p>Looping is not what the database or storage architecture are designed for, and even in SQL Server 2005, you are not going to get performance anywhere close to you get if you pull the basic data set out into a custom program and do the looping in memory, using data objects/structures that are as lightweight as possible.</p>\n'}, {'answer_id': 58154, 'author': 'Josef', 'author_id': 5581, 'author_profile': 'https://Stackoverflow.com/users/5581', 'pm_score': 8, 'selected': True, 'text': "<p>Because cursors take up memory and create locks.</p>\n\n<p>What you are really doing is attempting to force set-based technology into non-set based functionality. And, in all fairness, I should point out that cursors <em>do</em> have a use, but they are frowned upon because many folks who are not used to using set-based solutions use cursors instead of figuring out the set-based solution.</p>\n\n<p>But, when you open a cursor, you are basically loading those rows into memory and locking them, creating potential blocks. Then, as you cycle through the cursor, you are making changes to other tables and still keeping all of the memory and locks of the cursor open.</p>\n\n<p>All of which has the potential to cause performance issues for other users.</p>\n\n<p>So, as a general rule, cursors are frowned upon. Especially if that's the first solution arrived at in solving a problem.</p>\n"}, {'answer_id': 58160, 'author': 'Ash', 'author_id': 5023, 'author_profile': 'https://Stackoverflow.com/users/5023', 'pm_score': 2, 'selected': False, 'text': "<p>Cursors do have their place, however I think it's mainly because they are often used when a single select statement would suffice to provide aggregation and filtering of results.  </p>\n\n<p>Avoiding cursors allows SQL Server to more fully optimize the performance of the query, very important in larger systems.</p>\n"}, {'answer_id': 58161, 'author': 'Brannon', 'author_id': 5745, 'author_profile': 'https://Stackoverflow.com/users/5745', 'pm_score': 2, 'selected': False, 'text': '<p>Sometimes the nature of the processing you need to perform requires cursors, though for performance reasons it\'s always better to write the operation(s) using set-based logic if possible.</p>\n\n<p>I wouldn\'t call it "bad practice" to use cursors, but they do consume more resources on the server (than an equivalent set-based approach) and more often than not they aren\'t necessary.  Given that, my advice would be to consider other options before resorting to a cursor.</p>\n\n<p>There are several types of cursors (forward-only, static, keyset, dynamic). Each one has different performance characteristics and associated overhead.  Make sure you use the correct cursor type for your operation.  Forward-only is the default.</p>\n\n<p>One argument for using a cursor is when you need to process and update individual rows, especially for a dataset that doesn\'t have a good unique key.  In that case you can use the FOR UPDATE clause when declaring the cursor and process updates with UPDATE ... WHERE CURRENT OF.</p>\n\n<p>Note that "server-side" cursors used to be popular (from ODBC and OLE DB), but ADO.NET does not support them, and AFAIK never will.</p>\n'}, {'answer_id': 58165, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 2, 'selected': False, 'text': "<p>There are very, very few cases where the use of a cursor is justified.  There are almost no cases where it will outperform a relational, set-based query.  Sometimes it is easier for a programmer to think in terms of loops, but the use of set logic, for example to update a large number of rows in a table, will result in a solution that is not only many less lines of SQL code, but that runs much faster, often <em>several orders of magnitude</em> faster.</p>\n\n<p>Even the fast forward cursor in Sql Server 2005 can't compete with set-based queries.  The graph of performance degradation often starts to look like an n^2 operation compared to set-based, which tends to be more linear as the data set grows very large.</p>\n"}, {'answer_id': 3024251, 'author': 'Daniel P', 'author_id': 346593, 'author_profile': 'https://Stackoverflow.com/users/346593', 'pm_score': 5, 'selected': False, 'text': '<p>The above comments about SQL being a set-based environment are all true. However there are times when row-by-row operations are useful. Consider a combination of metadata and dynamic-sql.</p>\n\n<p>As a very simple example, say I have 100+ records in a table that define the names of tables that I want to copy/truncate/whatever. Which is best? Hardcoding the SQL to do what I need to? Or iterate through this resultset and use dynamic-SQL (sp_executesql) to perform the operations?</p>\n\n<p>There is no way to achieve the above objective using set-based SQL.</p>\n\n<p>So, to use cursors or a while loop (pseudo-cursors)?</p>\n\n<p>SQL Cursors are fine as long as you use the correct options:</p>\n\n<p>INSENSITIVE will make a temporary copy of your result set (saving you from having to do this yourself for your pseudo-cursor).</p>\n\n<p>READ_ONLY will make sure no locks are held on the underlying result set. Changes in the underlying result set will be reflected in subsequent fetches (same as if getting TOP 1 from your pseudo-cursor).</p>\n\n<p>FAST_FORWARD will create an optimised forward-only, read-only cursor.</p>\n\n<p>Read about the available options before ruling all cursors as evil.</p>\n'}, {'answer_id': 6052778, 'author': 'Gayan', 'author_id': 760195, 'author_profile': 'https://Stackoverflow.com/users/760195', 'pm_score': 2, 'selected': False, 'text': "<p>@ Daniel P -> you don't need to use a cursor to do it. You can easily use set based theory to do it. Eg: with Sql 2008</p>\n\n<pre><code>DECLARE @commandname NVARCHAR(1000) = '';\n\nSELECT @commandname += 'truncate table ' + tablename + '; ';\nFROM tableNames;\n\nEXEC sp_executesql @commandname;\n</code></pre>\n\n<p>will simply do what you have said above. And you can do the same with Sql 2000 but the syntax of query would be different.</p>\n\n<p>However, my advice is to avoid cursors as much as possible.</p>\n\n<p>Gayam</p>\n"}, {'answer_id': 6768633, 'author': 'Zorkind', 'author_id': 854213, 'author_profile': 'https://Stackoverflow.com/users/854213', 'pm_score': 4, 'selected': False, 'text': "<p>There is a work around about cursors that I use every time I need one.</p>\n\n<p>I create a table variable with an identity column in it.</p>\n\n<p>insert all the data i need to work with in it.</p>\n\n<p>Then make a while block with a counter variable and select the data I want from the table variable with a select statement where the identity column matches the counter.</p>\n\n<p>This way i dont lock anything and use alot less memory and its safe, i will not lose anything with a memory corruption or something like that.</p>\n\n<p>And the block code is easy to see and handle.</p>\n\n<p>This is a simple example:</p>\n\n<pre><code>DECLARE @TAB TABLE(ID INT IDENTITY, COLUMN1 VARCHAR(10), COLUMN2 VARCHAR(10))\n\nDECLARE @COUNT INT,\n        @MAX INT, \n        @CONCAT VARCHAR(MAX), \n        @COLUMN1 VARCHAR(10), \n        @COLUMN2 VARCHAR(10)\n\nSET @COUNT = 1\n\nINSERT INTO @TAB VALUES('TE1S', 'TE21')\nINSERT INTO @TAB VALUES('TE1S', 'TE22')\nINSERT INTO @TAB VALUES('TE1S', 'TE23')\nINSERT INTO @TAB VALUES('TE1S', 'TE24')\nINSERT INTO @TAB VALUES('TE1S', 'TE25')\n\nSELECT @MAX = @@IDENTITY\n\nWHILE @COUNT &lt;= @MAX BEGIN\n    SELECT @COLUMN1 = COLUMN1, @COLUMN2 = COLUMN2 FROM @TAB WHERE ID = @COUNT\n\n    IF @CONCAT IS NULL BEGIN\n        SET @CONCAT = '' \n    END ELSE BEGIN \n        SET @CONCAT = @CONCAT + ',' \n    END\n\n    SET @CONCAT = @CONCAT + @COLUMN1 + @COLUMN2\n\n    SET @COUNT = @COUNT + 1\nEND\n\nSELECT @CONCAT\n</code></pre>\n"}, {'answer_id': 30964726, 'author': 'Erik Hart', 'author_id': 832306, 'author_profile': 'https://Stackoverflow.com/users/832306', 'pm_score': 3, 'selected': False, 'text': '<p>Cursors are usually not the disease, but a symptom of it: not using the set-based approach (as mentioned in the other answers).</p>\n\n<p>Not understanding this problem, and simply believing that avoiding the "evil" cursor will solve it, can make things worse.</p>\n\n<p>For example, replacing cursor iteration by other iterative code, such as moving data to temporary tables or table variables, to loop over the rows in a way like:</p>\n\n<pre><code>SELECT * FROM @temptable WHERE Id=@counter \n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT TOP 1 * FROM @temptable WHERE Id&gt;@lastId\n</code></pre>\n\n<p>Such an approach, as shown in the code of another answer, makes things much worse and doesn\'t fix the original problem. It\'s an anti-pattern called <em>cargo cult programming</em>: not knowing WHY something is bad and thus implementing something worse to avoid it! I recently changed such code (using a #temptable and no index on identity/PK) back to a cursor, and updating slightly more than 10000 rows took only 1 second instead of almost 3 minutes. Still lacking set-based approach (being the lesser evil), but the best I could do that moment.</p>\n\n<p>Another symptom of this lack of understanding can be what I sometimes call "one object disease": database applications which handle single objects through data access layers or object-relational mappers. Typically code like:</p>\n\n<pre><code>var items = new List&lt;Item&gt;();\nforeach(int oneId in itemIds)\n{\n    items.Add(dataAccess.GetItemById(oneId);\n}\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>var items = dataAccess.GetItemsByIds(itemIds);\n</code></pre>\n\n<p>The first will usually flood the database with tons of SELECTs, one round trip for each, especially when object trees/graphs come into play and the infamous SELECT N+1 problem strikes.</p>\n\n<p>This is the application side of not understanding relational databases and set based approach, just the same way cursors are when using procedural database code, like T-SQL or PL/SQL!</p>\n'}]
['https://Stackoverflow.com/questions/58141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5469/']