简体   繁体   中英

Get value from anonymous block inside a procedure in oracle

I have created a stored procedure which calls a function which returns boolean.

We are getting the schema name the function is under at run time, so we are creating the statement as a string by concatenation, and executing the function in an anonymous block dynamically.

CREATE OR REPLACE PROCEDURE usp_proc
(
        variable declarations
)
as
var1 varchar2(50);
var2 varchar2(50);
var3 varchar3(50);
begin
    execute immediate
        'declare result boolean ; ConversionFactor number; res varchar2(10); begin  result:= '||schemaname||'fn_name('''||var1||''', '''||var2||''',ConversionFactor,'''||var3||''');'||
                    ' if(result=False) then res:=''False'';'||
                    ' ELSE res:=''True''; END IF; end;';

    stmt:='select Weight*ConversionFactor  from table'
       Open cur for stmt;   
    END;

I need to use the ConversionFactor variable outside the anonymous block. How can I gets its value to use later in the procedure?

Rather than define ConversionFactor as a local variable inside your dynamic PL/SQL block, you can declare it in your procedure and pass it as an OUT bind variable . You can get the res value back the same way too. Your var1 , var2 and var3 values can/should be passed as bind variables as well, rather than concatenating them into the call.

Demo using an anonymous block instead of a procedure, as yours has some other things wrong anyway, and a dummy function in the specified schema:

declare
  var1 varchar2(50);
  var2 varchar2(50);
  var3 varchar2(50);
  schemaname varchar2(30);
  res varchar2(5);
  ConversionFactor number;
begin
  schema := 'SOME_SCHEMA';
  -- also assign values to var1, var2 and var, presumably

  execute immediate
    'declare result boolean;'
      || 'begin'
      || ' result := '||schemaname||'.fn_name(:var1, :var2, :ConversionFactor, :var3);'
      || ' :res := case when result then ''True'' else ''False'' end;'
      || 'end;'
  using var1, var2, out ConversionFactor, var3, out res;

  dbms_output.put_line('Got result: ' || res);
  dbms_output.put_line('Got ConversionFactor: ' || ConversionFactor);
end;
/

Got result: True
Got ConversionFactor: 42

PL/SQL procedure successfully completed.

Note the out ConversionFactor , and the out res , so mark them as OUT bind variables. The others are left to default to IN . (I've also added a missing period between the schema and function names).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM