As others have pointed out, prepared statements and cursors are not
mutually exclusive.
There are however two pairs of concepts in SQL that you need to understand.
Static vs. Dynamic (prepared)
Sets vs. Cursors
//static - BEST
exec sql
select count(*) into :totrows
from mytable
where fld1 = :somevalue;
//dynamic - with parameter markers '?') - GOOD
// note: SELECT INTO can not be used dynamically
wSqlStm = 'values (select count(*) from mytable where fld1 = ?) into ?';
exec sql
prepare s1 from :wSQLstmt;
exec sql
execute s1 using :somevalue, :totrows;
//dyanmic - without parameter markers - VERY BAD, SQL Injection time
// see how I'm directly concatenating user input into the statement
wSqlStm = 'values (select count(*) from mytable where fld1 = '
+ '''' + somevalue + '''' + ')';
exec sql
prepare s1 from :wSQLstmt;
exec sql
execute s1;
//Sets - update all records at once
exec sql
update payroll
set salary = salary * 1.1;
//Cursor - update all records, one row at a time.
exec sql
declare C1 cursor for
select salary
from payroll;
exec sql
open C1;
dow moreRows;
exec sql
fetch next from C1 into :wSalary;
wSalary = wSalary * 1.1;
exec sql
update payroll
set salary = :wSalary
where current of cursor C1;
enddo;
The examples are contrived, but hopefully you'll see it'd be silly to use a
cursor.
The problem is that lots of code you'll find will use cursors when it
doesn't really need to. And it may not be as obvious. Cursors are
familiar, especially to developers coming from a RLA row-by-row processing
background.
Try to remember the following quotes from Jeff Moden (even if he is a MS
SQL server guy)
"*RBAR* is pronounced "ree-bar" and is a "Modenism" for "*R*ow-*B*y-*A*
gonizing-*R*ow".
"First step towards the paradigm shift of writing Set Based code:
*Stop thinking about what you want to do to a row... think, instead, of
what you want to do to a column." *
You absolutely need cursors in a few places
- to return data to a client app
- to print data
- to display data
Other than that, you should be avoiding them.
Charles
On Tue, Feb 16, 2016 at 3:48 PM, Booth Martin <booth@xxxxxxxxxxxx> wrote:
I am involved in a discussion of the pros & cons of Prepared Statements
and Cursors. Clearly I am over my head.
What are the strengths/weaknesses of these two solutions? Which do you
prefer?
--
This is the RPG programming on the IBM i (AS/400 and iSeries) (RPG400-L)
mailing list
To post a message email: RPG400-L@xxxxxxxxxxxx
To subscribe, unsubscribe, or change list options,
visit: http://lists.midrange.com/mailman/listinfo/rpg400-l
or email: RPG400-L-request@xxxxxxxxxxxx
Before posting, please take a moment to review the archives
at http://archive.midrange.com/rpg400-l.
Please contact support@xxxxxxxxxxxx for any subscription related
questions.
As an Amazon Associate we earn from qualifying purchases.