-1

How can I assign a variable dynammically in PL/SQL?

I tried something like this, which doesn't work:

declare
   v_variable number := execute immediate 'select max(value) from mytable';
begin
   dbms_output.put(v_variable);
end;

How could this be done?

royskatt
  • 1,190
  • 2
  • 15
  • 35

2 Answers2

2

Just assign it in the body of the code, not in the declaration. Also, you're not using any dynamic SQL, so no need for EXECUTE IMMEDIATE..

declare
   v_variable number;
begin

   select max(value) 
   into v_variable
   from mytable;

   dbms_output.put(v_variable);
end;
StevieG
  • 8,639
  • 23
  • 31
1

You can only assign variable values to variables in the execution (after begin) part of the code. For instance, the following (taken from https://stackoverflow.com/a/9957933/150533) swaps values from two variables:

declare
  no1 number(3):=31;
  no2 number(3):=34;
  temp number;
begin
  dbms_output.put_line('Before swap');
  dbms_output.put_line('No1 : '||no1||'  No2 : '||no2 );
  --  no1:=(no1+no2)-(no2:=no1);  generate error
  temp := no1;
  no1 := no2;
  no2 : temp;
  dbms_output.put_line('After swap');
  dbms_output.put_line('No1 : '||no1||'  No2 : '||no2 );
end;
Community
  • 1
  • 1
kurast
  • 1,660
  • 3
  • 17
  • 38