Are PL/SQL variables in cursors effectively the same as bind parameters?

余生颓废 提交于 2019-11-29 11:45:02

First of all, good question.

I would like to make a small quote:

Every reference to a PL/SQL variable is in fact a bind variable.

Having said that,

PL/SQL itself takes care of most of the issues to do with bind variables, to the point where most code that you write already uses bind variables without you knowing. Take, for example, the following bit of PL/SQL:

create or replace procedure dsal(p_empno in number)
as
  begin
    update emp
    set sal=sal*2
    where empno = p_empno;
    commit;
  end;
/

Now you might be thinking that you've got to replace the p_empno with a bind variable. However, the good news is that every reference to a PL/SQL variable is in fact a bind variable.

Source

Reading the fine manual: PL/SQL Static SQL

A PL/SQL static SQL statement can have a PL/SQL identifier wherever its SQL counterpart can have a placeholder for a bind variable. The PL/SQL identifier must identify either a variable or a formal parameter.

Both of your example snippets are equivalent from SQL engine point of view and perform equally well.

Reading more the same fine manual:

Generally, PL/SQL parses an explicit cursor only the first time the session opens it and parses a SQL statement (creating an implicit cursor) only the first time the statement runs.

All parsed SQL statements are cached. A SQL statement is reparsed only if it is aged out of the cache by a new SQL statement. Although you must close an explicit cursor before you can reopen it, PL/SQL need not reparse the associated query. If you close and immediately reopen an explicit cursor, PL/SQL does not reparse the associated query.

So changing the bind variable requires no SQL statement parsing.

From code readability (i.e. maintenance) point of view the second snippet that is using parameters is superior. It's not obvious in small snippets but in large PL/SQL programs it's a headache if cursors directly use package or subroutine variables. When reading code one needs every time check what is the state the cursor depends on. With cursor parameters one sees that immediatelly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!