The basic rule of thumb is to never use a cursor. Its not because of a memory leak, as there isn’t one; there is a performance issue with using cursors.
SQL Server handles its data in recordsets. It is designed to more efficiently process data in recordsets than row by row.
In the case of your example.
<pre>SELECT ‘exec sp_detach_db ‘ + name
WHERE name NOT IN (‘master’, ‘model’, ‘msdb’, ‘tempdb’)</pre>
Will spit out the code that you need without a cursor.
There are cases when cursors are the best option for example when you want to run a stored procedure for every row in the recordset a cursor will be the best way, unless you can modify the stored procedure to accept an XML document or User Defined Data Type of TABLE as an input parameter then be able to run the entire thing in a single batch.