10 June 2006

Column And Variable Scopes In PL/SQL



Geçenlerde bir fonksiyon yazmam gerekiyordu. Fonksiyon içine gelen parametre adını, yine o fonksiyon içinde kullandığım bir tablonun kolon ismi aynı vermiştim. Bu kolon isminin WHERE koşulu içinde istenmeyen bir durum oluşturduğunu gördüm. İlgili fonksiyon tek bir satır içeren cursor döndürmesi gerekirken çoklu sayıda kayıt döndüren cursor gelmekteydi. İlgili arkadaşın uyarması ile durumu çözdüm. Öncelik sırası olarak kolon isimlerinin, değişken isimlerinden daha etkili olduğunu farkettim. Aşağıdaki PL/SQL bloğunda bu durum görülebilir.
create table scope_test as select * from all_objects ao where rownum <= 100

SELECT count(*) FROM scope_test
--100

DECLARE
  object_id   NUMBER;
  tscope_test scope_test%ROWTYPE;
  i           NUMBER;
BEGIN
  object_id :=
258;
  i         :=
0 ;
  FOR tscope_test IN (SELECT *
                        FROM scope_test st
                       WHERE st.object_id = object_id) LOOP
    i := i +
1;
  END LOOP;
  dbms_output.put_line(i);
 
--100

END;

DECLARE
  nobject_id  NUMBER;
  tscope_test scope_test%ROWTYPE;
  i           NUMBER;
BEGIN
  nobject_id :=
258;
  i         :=
0;
  FOR tscope_test IN ( SELECT *
                        FROM scope_test st
                       WHERE st.object_id = nobject_id) LOOP
    i := i +
1;
  END LOOP;
  dbms_output.put_line(i);
 
--1

END;