Question

I write below script and I get ORA-01722 error at line 8. How can I solve this error? thanks in advance.

declare 
  type array_t is varray(2) of VARCHAR2(20);
  array array_t := array_t('5634', '5764');

 begin

  for i in 1..array.count loop   
      execute immediate 'select t.musteri_id from tms.isemri t where t.isemri_tarihi  = (select max(t.isemri_tarihi) from tms.isemri t where t.hizmet_no = '|| 
      array(i)||') and t.hizmet_no ='|| array(i);   

  end loop;
  end;
Was it helpful?

Solution

execute immediate 'select t.musteri_id from tms.isemri t where t.isemri_tarihi = (select max(t.isemri_tarihi) from tms.isemri t where t.hizmet_no = '''|| array(i)||''') and t.hizmet_no ='''|| array(i)||'''';

OTHER TIPS

Your concatenated SQL will look like:

select t.musteri_id from tms.isemri t where t.isemri_tarihi =
(select max(t.isemri_tarihi) from tms.isemri t where t.hizmet_no = 5634)
and t.hizmet_no = 5634

Note that the value 5634 is a number not a string, and this causes Oracle to implcitly cast hizmet_no to a number, which will not always work.

You should be using bind variables, which will fix this issue:

declare 
  type array_t is varray(2) of VARCHAR2(20);
  array array_t := array_t('5634', '5764');
  l_musteri_id tms.isemri.musteri_id%type
 begin

  for i in 1..array.count loop   
      execute immediate 'select t.musteri_id from tms.isemri t 
                         where t.isemri_tarihi  = (select max(t.isemri_tarihi)
                                                   from tms.isemri t
                                                   where t.hizmet_no = :val1)
                         and t.hizmet_no = :val2'
       into l_musteri_id
       using array(i), array(i);   

  end loop;
  end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top