SQL Server developers consider Cursors a bad practise , except under some circumstances. They believe that Cursors do not use the SQL engine optimally since it is a procedural construct and defeats the Set based concept of RDBMS.
However, Oracle developers do not seem to recommend against Cursors. Oracle’s DML statements themselves are implicit cursors.
Why this difference in approach? Is it because of the way these 2 products are made, or does this advice apply to both products?
What’s wrong with cursors is that they are often abused, both in
Oracleand inMS SQL.Cursor are for keeping a stable resultset which you can retrieve row-by-row. They are implicitly created when your query is run, and closed when it’s finished.
Of course keeping such a resultset requires some resources:
locks,latches,memory, evendisk space.The faster these resources are freed, the better.
Keeping a cursor open is like keeping a fridge door open
You don’t do it for hours without necessity, but it does not mean you should never open your fridge.
That means that:
SQL‘sSUMinstead.rownum <= 10condition to your query, etc.
As for
Oracle, processing your cursors inside a procedure requires infamousSQL/PLSQL context switchwhich happens every time you get a result of anSQLquery out of the cursor.It involves passing large amounts of data between threads and synchronizing the threads.
This is one of the most irritating things in
Oracle.One of the less evident consequences of that behaviour is that triggers in Oracle should be avoided if possible.
Creating a trigger and calling a
DMLfunction is equal to opening the cursor selecting the updated rows and calling the trigger code for each row of this cursor.Mere existence of the trigger (even the empty trigger) may slow down a
DMLoperation10 timesor more.A test script on
10g:1.47seconds without a trigger,17.57seconds with an empty trigger doing nothing.