Monday, October 14, 2013

bind variables in pl-sql.

This example illustrate that how bind variables enhance performance.

Note: Bind variables are explicitly used if you are using pl-sql variables. If you are using dynamic sql(execute immediate) then only you have to use bind variables in pl-sql.

alter system flush shared_pool;
set serveroutput on;

declare
      type rc is ref cursor;
      l_rc rc;
      l_dummy all_objects.object_name%type;
      l_start number default dbms_utility.get_time;
  begin
      for i in 1 .. 1000
      loop
          open l_rc for
          'select object_name
             from all_objects
            where object_id = ' || i;
          fetch l_rc into l_dummy;
          close l_rc;
          -- dbms_output.put_line(l_dummy);
      end loop;
      dbms_output.put_line
       (round((dbms_utility.get_time-l_start)/100, 2) ||
        ' Seconds...' );
  end;
/


declare
      type rc is ref cursor;
      l_rc rc;
      l_dummy all_objects.object_name%type;
      l_start number default dbms_utility.get_time;
  begin
      for i in 1 .. 1000
      loop
          open l_rc for
          'select object_name
             from all_objects
            where object_id = :x'
          using i;
          fetch l_rc into l_dummy;
          close l_rc;
          -- dbms_output.put_line(l_dummy);
      end loop;
      dbms_output.put_line
       (round((dbms_utility.get_time-l_start)/100, 2) ||
        ' Seconds...' );
end;
/

http://www.akadia.com/services/ora_bind_variables.html


The most important question to ask is: What is wrong with this statement? 'SELECT * FROM t WHERE pk='||v_identifier If you don't hear something back about bind variables or hard parses you are talking to a junior developer.