Executing stored procedure dynamically

Hi Everybody,
I am trying to execute one procedure in other procedure dynamically. I am not sure, how to do this. Please provide your responses and comments.
Main Sp:
CREATE OR REPLACE PROCEDURE R2D2.SP_UPDATE (
V_ID IN RC_PENDING_TX.CS_ID%TYPE,
S_ID IN RC_PENDING_TX_STATUS_VL.STATUS_ID%TYPE,
A_ID IN VARCHAR2,
V_NOTES IN VARCHAR2
IS
v_date DATE := SYSDATE;
db_id varchar2(10);
stmt varchar2(10000);
stmt1 varchar2(10000);
BEGIN
db_ID := get_id(v_ID);
IF S_ID = 1
THEN
stmt:= 'begin utl_pkg.set_v_id@'||db_id||'('||V_ID||','||'1'||'); end;';
stmt1:= 'begin utl_pkg.set_t_id@'||db_id||'('||V_ID||','||'1,2,3,4'||','||'Y'||');end;';
execute immediate stmt;
execute immediate stmt1;
END IF;
END SP_UPDATE;
1) GET_ID IS function to get db_id for v_id.
2)utl_pkg.set_v_id,utl_pkg.set_t_id two sps i need to execute if s_id = 1.
3) I have to execute both sps utl_pkg.set_v_id, utl_pkg.set_t_id , which take v_id as input parameter from main sp and these sps will execute in db with db link db_id (which we get from function for v_id we pass in main sp).
Please let me know, how i can do this. DO i need to do it dynamically or i can do it in some ways.
Please help me guys. I will really appreciate it.
Thank you in advance.

Try this.
Please see closely commas and parameter passed in procedures.
SQL> select name from v$database;
NAME
ORADB1
SQL> create or replace package UTL_PKG is
  2   procedure set_v_id(v_id varchar2,any_value varchar2);
  3 
  4  end UTL_PKG;
  5  /
Package created.
SQL> create or replace package body UTL_PKG is
  2 
  3    Procedure set_v_id( v_id varchar2,any_value varchar2 )is
  4     
  5    begin
  6       
  7    dbms_output.put_line('Package from remote DB'||v_id ||' '||any_value);   
  8       
  9    end;
10 
11  end UTL_PKG;
12  /
Package body created.
SQL> Now on another DB
SQL> select name from v$database;
NAME
ORADB2
SQL> select db_link,host from all_db_links;
DB_LINK                HOST
DB1_LINK              ORADB1  
SQL> CREATE OR REPLACE PROCEDURE SP_UPDATE (
  2  V_ID IN emp.ename%TYPE, --This datatype is VARCAHR2
  3  S_ID IN emp.empno%TYPE, --This datatype is NUMBER
  4  A_ID IN VARCHAR2,
  5  V_NOTES IN VARCHAR2
  6  )
  7  IS
  8  v_date DATE := SYSDATE;
  9  db_id varchar2(100);
10  stmt varchar2(1000);
11  BEGIN
12 
13  select db_link into db_id from ALL_DB_LINKS   -- Assuming only DB link is present
14 
15 
16  IF S_ID = 1 THEN
17  
18   stmt:= 'begin utl_pkg.set_v_id@'||db_id||'('||''''||v_id||''''||','||'''1'''||'); end;';
19   dbms_output.put_line(stmt);
20   execute immediate stmt;
21  END IF;
22 
23  END SP_UPDATE;
24  /
Procedure created.
SQL> show error;
No errors.
SQL>  begin
  2     SP_UPDATE('1',1,'a','sometext');
  3     end;
  4  /
begin utl_pkg.set_v_id@ORADB1('1','1'); end;
PL/SQL procedure successfully completed.
SQL> show error
No errors.
SQL> Edited by: Azhar Husain on Jun 10, 2011 1:16 PM

Similar Messages

  • How can I execute Stored Procedures in PARALLEL and DYNAMICALLY ?

    Hi 
    I have a stored procedure. It can be executed like this
    exec test @p = 1;
    exec test @p = 2
    exec test @p = n;
    n can be hundred.
    I want the sp being executed in parallel, not sequence. It means the 3 examples above can be run at the same time.
    If I know the number in advance, say 3, I can create 3 different Execution SQL Tasks. They can be run in parallel.
    However, the n is not static. It is coming from a table. 
    How can I execute Stored Procedures in PARALLEL and DYNAMICALLY ?
    I think about using script task. In the script, I get the value of n, and the list of p, from the table, then running a loop with. In the loop, I create a threat and in the threat, I execute the sp like : exec test @p = p. So the exec test may
    be run parallel. But I am not sure if it works.
    Any idea is really appreciated.

    Hi nam_man,
    According to your description, you want to call stored procedures in parallel, right?
    In SSIS, we can create separate jobs with different stored procedures, then set the same schedule to kick the jobs off at the same time. In this way, we should be careful to monitor blocking and deadlocking depending on what the jobs are doing.
    We can also put all stored procedures in SSIS Sequence container, then they will be run in parallel.
    For more information about SSIS job and Sequence container, please refer to the following documents:
    http://www.mssqltips.com/sqlservertutorial/220/scheduling-ssis-packages-with-sql-server-agent/
    https://msdn.microsoft.com/en-us/library/ms139855(v=sql.110).aspx
    If you have any more questions, please feel free to ask.
    Thanks,
    Wendy Fu
    Wendy Fu
    TechNet Community Support

  • Calling SQL stored procedure dynamically

    Hallo,
    could anybody tell me how to call HANA SQL stored procedure dynamically?
    The coding looks like this:
    v_ProcedureName := '"' || KpiNamespace || '::' || KpiName || '"';
    v_SQL := 'CALL ' || :v_ProcedureName || '( lt_outKPI )';
    EXEC :v_SQL;
    For this call I get the error message:
    "Transaction rolled back by an internal error: wrong number or types of parameters in call: Physical table is not allowed in OUT table variable position: LT_OUTKPI: line 1 col 55 (at pos 54)"
    The procedure to be called dynamically has a table output parameter.
    Thanks in advance,
    Best Regards,
    Alexey Romanov.
    Hi Alex,
    Can you share your requirement on exactly what is the need to call the procedure dynamically?
    For your question, have a look on the below:
    1) Have a procedure named EMPLOYEE_DETAILS
    http://scn.sap.com/servlet/JiveServlet/downloadImage/2-14895702-415799/236-170/pastedImage_0.png
    2) Created one more procedure named Dynamically as shown below:
    CREATE PROCEDURE Dynamically ()
    AS
    BEGIN
    DECLARE QUERY VARCHAR(1000);
    QUERY := 'call  EMPLOYEE_DETIALS(?)';
    EXECUTE IMMEDIATE (:QUERY);
    END;
    3) Output:
    http://scn.sap.com/servlet/JiveServlet/downloadImage/2-14895702-415800/210-189/pastedImage_3.png
    Regards,
    Krishna Tangudu
    Hi Krishna,
    Thanks for your reply!
    Unfortunately, I can neither go to ‘full discussion’, nor open the pictures, you have attached, nor see you reply.
    That’s why I just add my reply to the problem description.
    The procedure name is composed out of 2 parts on-the-fly, that is why I have to call it dynamically:
    create local temporary table "#KPIEvals"(           
              "KpiNamespace" NVARCHAR(256) CS_STRING,           
              "KpiName" NVARCHAR(32) CS_STRING,               
              "KpiText" NVARCHAR(256) CS_STRING,           
              "Responsible" NVARCHAR(256) CS_STRING );
    FOR cur_row as c_cursor DO        
         v_SQL := '';     
         v_ProcedureName :=  '"' || cur_row."KpiNamespace" || '::' || cur_row."KpiName" || '"';     
         v_SQL := 'CALL ' || :v_ProcedureName || '( lt_outKPI )';     
         EXEC :v_SQL;                
         v_SQL := 'INSERT INTO "#KPIEvals" SELECT * FROM :lt_out_kpi';     
         EXEC :v_SQL;                
    END FOR;
    I guess there might be 2 reasons for the problem:
    1.     All the procedures are called dynamically in a loop.
    2.     All the procedures have an output parameter, which is a table.
    Hope that helps,
    Best Regards,
    Alex.

    Hi Alexey, I think what you may need to do in this case is to do the insert into your temp table from within the dynamically called procedure, therefore no need for output param in your procedure call. You can then select from the temp table in your main procedure. Hope that makes sense.
    Peter

  • How to run oracle stored procedure dynamically

    How can I call a stored procedure dynamically. My requirement is to call a stored procedure based on user selection on a parameter screen. I do not want to hardcode proocedure name, but rather call dynamically.
    If I use the same methodology as of running dynamic sql's Iam getting an error.
    "invalid SQL statement after call to procedure"
    v_cursorid INTEGER;
    v_cnt NUMBER;
    v_sqlstring VARCHAR2(2000);
    v_sqlstring := 'execute insert_job_status('''||TO_CHAR(SYSDATE,
    'dd-mon-yyyy HH:mi:ss')||''');';
    v_cursorid := dbms_sql.open_cursor;
    dbms_sql.parse(v_cursorid, v_sqlstring, dbms_sql.v7);
    --cnt        := dbms_sql.execute(v_cursorid);
    dbms_sql.close_cursor(v_cursorid);

    EXECUTE is a SQL*Plus command. try
    v_sqlstring := 'begin  insert_job_status('''||TO_CHAR(SYSDATE,
    'dd-mon-yyyy HH:mi:ss')||'''); end;';Cheers, APC

  • In JDBC Sender Adapter , the server is Microsoft SQL .I need to pass current date as the input column while Executing stored procedure, which will get me 10 Output Columns. Kindly suggest me the SQL Query String

    In JDBC Sender Adapter , the server is Microsoft SQL .I need to pass current date as the input column while Executing stored procedure, which will get me 10 Output Columns. Kindly suggest me the SQL Query String , for executing the Stored Procedure with Current date as the input .

    Hi Srinath,
    The below blog might be useful
    http://scn.sap.com/community/pi-and-soa-middleware/blog/2013/03/06/executing-stored-procedure-from-sender-adapter-in-sap-pi-71
    PI/XI: Sender JDBC adapter for Oracle stored procedures in 5 days
    regards,
    Harish

  • Found a bug in "Execute Stored Procedure..." command

    Hi...I've found one interesting "feature": if I do click "Execute Stored Procedure"on SP, which contains an XML parameter (doesn't matter if it's input or output), Management Studio generates script without declaring datatype of that
    parameter. But if I click "Generate Script" everything works fine. This situation can be observed in SQL Server 2005-2012.

    Hello,
    Please submit a product feedback on Microsoft Connect:
    https://connect.microsoft.com/sqlServer/
    Thank you for sharing what you have discovered.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Problem in executing Stored Procedure from Trigger

    Hi,
    Case1.
    I am executing a stored procedure form a trigger. The stored procedure is not executing fully.
    Case 2.
    But when when I execute Stored Procedure alone it is executing.
    CREATE OR REPLACE TRIGGER mhubadmin.call_proc_ratesheet_new
    after INSERT OR delete ON mhubadmin.pvt_br_ratesheet
    FOR EACH ROW
    declare
    var_orgid number;
    begin
    if inserting then
    select org_child_id into var_orgid from business_relationship where br_id=:new.br_id;
    mhubadmin.proc_ratesheet_new(var_orgid);
    else
    select org_child_id into var_orgid from business_relationship where br_id=:old.br_id;
    mhubadmin.proc_ratesheet_new(var_orgid);
    end if;
    end;
    CREATE OR REPLACE PROCEDURE proc_ratesheet_new(var_orgid in number)
    IS
    cursor c3 is select distinct(purs.user_id) from hubuser hu
    inner join PVT_USER_RATESHEET purs on hu.USER_ID=purs.USER_ID
                   where hu.ORG_ID=var_orgid;
    cursor c1(varUser_id number) is select purs.user_id,purs.ratesheet_id from hubuser hu
    inner join PVT_USER_RATESHEET purs on hu.USER_ID=purs.USER_ID
                   where hu.ORG_ID=var_orgid and purs.USER_ID=varUser_id;
    cursor c2(varUser_id number) is select hu.user_id,pbr.ratesheet_id from HUBUSER hu
                             inner join BUSINESS_RELATIONSHIP br on hu.ORG_ID=br.ORG_CHILD_ID
                             inner join PVT_BR_RATESHEET pbr on br.BR_ID=pbr.BR_ID
                                  where hu.user_id in(select distinct(purs.USER_ID) from hubuser hu
                                       inner join PVT_USER_RATESHEET purs
                                                                     on hu.USER_ID=purs.USER_ID
                                                 where hu.ORG_ID=var_orgid) and hu.user_id=varUser_id;
    foundFlag boolean;
    incrFound integer;
    insertFound integer;
    deleteFound integer;
    str varchar2(4000);
    BEGIN
         incrFound:=0;
         insertFound:=0;
         for c3var in c3 loop
    for c2var in c2(c3var.user_id) loop
              insert into test values ('Step3:'||c2var.user_id);
              foundFlag:=false;
              for c1var in c1(c3var.user_id) loop
                   if c2var.ratesheet_id=c1var.ratesheet_id then
                        foundFlag:=true;
                             incrFound:=incrFound+1;
                             exit;
                        end if;
                   end loop;
                   if foundFlag=False then
                   --insert into pvt_user_ratesheet (username_ratesheet_id,user_id,ratesheet_id) values (SEQ_USER_RATESHEET.nextval,c3var.user_id,c2var.ratesheet_id);
                   dbms_output.put_line('Inserted for user :'||c3var.user_id||' is - ratesheet :'||c2var.ratesheet_id);
                   insertFound:=insertFound+1;
                   end if;
              end loop;
    end loop;
         commit;
         incrFound:=0;
         deleteFound:=0;
         for c3var in c3 loop
              for c1var in c1(c3var.user_id) loop
              foundFlag:=false;
              for c2var in c2(c3var.user_id) loop
                        if c1var.ratesheet_id=c2var.ratesheet_id then
                        foundFlag:=true;
                        incrFound:=incrFound+1;
                        exit;
                        end if;
                   end loop;
                   if foundFlag=False then
                   --delete from pvt_user_ratesheet where user_id=c3var.user_id and ratesheet_id=c1var.ratesheet_id;
                        --dbms_output.put_line('Deleted for userid:'||c3var.user_id||' for ratesheet :'||c1var.ratesheet_id);
                        deleteFound:=deleteFound+1;
                   end if;
              end loop;
    end loop;
         commit;
    EXCEPTION
    WHEN OTHERS THEN
    DBMS_OUTPUT.put_line (SQLCODE||' '|| SQLERRM);
    END;
    Regards,
    Mathew

    In general, I would suggest that you only catch errors that you can handle reasonably. If you know that a SELECT INTO might return 0 rows for example, handle the NO_DATA_FOUND exception. Having a WHEN OTHERS, particularly without re-raising the exception, only serves to hide the source of the problem. I would much rather that my code fail quickly and explicitly than hope that I see an error message in the output and that other code doesn't start failing because the system wasn't left in an appropriate state.
    As Mark suggests, you may choose to implement a comprehensive logging framework using autonomous transactions, in which case a WHEN OTHERS would be reasonable, but you would still want to propagate exceptions you cannot handle.
    If you see a WHEN OTHERS clause and there is no RAISE, you probably have an error waiting to happen.
    Justin

  • Execute stored procedure as sysadmin

    Hi,
    I am running powershell script to execute stored procedure on SQL server. Powershell script is run with low privilege user account on SQL server, but SP is restoring databases and requires sysadmin permissions. How can I execute SP with sysadmin permissions?
    Could this be done proxy account? without additional users creation. Any links? Thanks

    You can create the sp using a sysadmin account (or in dbo schema) and use EXECUTE AS OWNER inside it
    Then give the powershell account execute access to the procedure and it will run under context of dbo user  (or owner account) which will have necessary permission to do the data base restore etc
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Could not execute stored procedure in oracle

    hello experts,
    Problem: I can not execute stored procedures stored in Oracle data base. Error Message: Portal request failed. Could not execute stored procedure.
    My steps:
    i connected my locally installed Oracle data base to the VC. I mapped the data base user to my VC user. I tested connection and it is fine. Further I see the db alias in Visual Composer and i can drop stored procedures to my story board. I can define parameters, but when I am executing procedures I get the error message.
    Further I installed MS SQL Server lokally and connected to the VC and it is working fine. I can do everything.
    Why it is not working for Oracle DB?
    DriverName: com.sap.portals.jdbc.oracle.OracleDriver
    Connect-URL: jdbc:sap:oracle://ip:port;sid=XE
    Any comment is highly appreciated.
    anton.

    Hi,
    Also you can follow this link which explains you the procedure to configure BI JDBC system for visual composer.
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/6209b52e-0401-0010-6a9f-d40ec3a09424
    Regards
    Inder
    Do reward points if helpful.

  • Entity Framework - Execute Stored Procedures

    I want to execute stored procedure using entity framework.
    I am using entity framework 6.
    The stored procedure has SELECT and RETURN statement.
    How can I read the output from SELECT and RETURN statements using
    dbContext.Database.ExecuteSqlCommand or dbContext.Database.SqlQuery statement ?

    Hello Sumit Kadam,
    >> The stored procedure has SELECT and RETURN statement.
    For the select statement, Entity Framework would support natively:
    http://www.entityframeworktutorial.net/stored-procedure-in-entity-framework.aspx
    For the return statement, we could use the dbContext.Database.SqlQuery statement as below to fetch the value:
    var returnCode = new SqlParameter();
    returnCode.ParameterName = "@ReturnCode";
    returnCode.SqlDbType = SqlDbType.Int;
    returnCode.Direction = ParameterDirection.Output;
    // assign the return code to the new output parameter and pass it to the sp
    var data = db.Database.SqlQuery<Order>("exec @ReturnCode = ProGetOrder", returnCode);
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to customize events, execute stored procedures using JSF and ADF BC

    As a java beginner, I started with developing simple web application using JSF and ADF business component through visual and declarative approach. I need to know how to customize events, execute stored procedures, invoke functions on triggering events associated with rich controls. for eg. how to write customized functions on button click or checkbox click events to achieve business requirement and can be modified whenever required.
    Edited by: 792068 on Aug 31, 2010 9:40 PM

    Which business layer is prefered to create interactive data model: 1. ADF business components or 2. Enterprise JavaBeans using Java persistance API (JPA) or 3. Toplink 4. Portlets
    which minimizes writing low level codes and how much OOPS knowledge is required for creating above business layer binding data to viewcontroller layer?

  • Execute Stored Procedures from Stellent

    Can we execute stored procedures from stellent 7.5.2 ?
    By using java, I dont find any method to execute stored procedure from WorkSpace interface.
    Please guide me to solve this..
    Appreciate your help and efforts.

    May not be exactly what you're looking for, but I hope this helps:
    http://www.corecontentonly.com/Blog/Calling-A-Stored-Procedure-From-Oracle-Fusion-ECM-Stellent
    For java based execution basically:
    1. Create your stored proc in the db
    2. Create a component
    3. Create a query resource
    4. In your java code use the createResultSet method of the Workspace object and pass in the name of your query resource and then the current databinder object

  • Execute stored procedure from Unix shell script

    My current method of executing stored procedures (wpl_1 and wpl_2) from a unix shell script is as follows:
    <<wpl.sh>>
    sqlplus user/password @/home/oracle/scripts/wpl.sql
    <<wpl.sql>>
    set serveroutput on size 1000000
    set timing on
    execute wpl_1('0000010676','~')
    execute wpl_2('0000010676','~')
    execute wpl_1('0000010236','FIX')
    execute wpl_2('0000010236','FIX')
    exit
    Question: Is it possible to combine the two scripts (unix and oracle) together?

    A little rusty on this, but this may work:
    My current method of executing stored procedures
    (wpl_1 and wpl_2) from a unix shell script is as
    follows:
    <<wpl.sh>>sqlplus user/password @/home/oracle/scripts/wpl.sql << EOF
    set serveroutput on size 1000000
    set timing on
    execute wpl_1('0000010676','~')
    execute wpl_2('0000010676','~')
    execute wpl_1('0000010236','FIX')
    execute wpl_2('0000010236','FIX')
    exit
    EOF
    >
    Question: Is it possible to combine the two scripts
    (unix and oracle) together?

  • Call stored procedure dynamically?

    I wrote a bunch of programs in Perl to output different reports. All these programs are very similar: calling a stored procedure in SQL Server, dump the ResultSet into the file in disk ...
    My boss asked me to write a "Generic" program to combine these programs together so that we don't need write endless similar programs any more.
    I decide to write this program in Java. The new program is supposed to take a stored procedure call as an input parameter (reading from a configuration file, maybe?). It will be great if the program can dynamically determine the field names in the ResultSet from the stored procedure call. In another word, there shouldn't be any hard coded field names in the Java Code. The more generic of the program, the better.
    Is this doable? Does anyone have any such experience before? Any idea or recommendation is highly appreciated.
    Thanks a lot,
    - LX

    Here is some that I wrote:
    //Here is a snippet out of my main program:
                   md = rs.getMetaData();
                   noOfColumns = md.getColumnCount();     
                   //Generate the sql for our prepared statement insert
                   sql = buildInsertSQL("DWXP111", noOfColumns);
                   lowLevel.info("SQL:" + sql);
                   //Create the prepared statment
                   ps = legacyCon.prepareStatement(sql);
                   //Set the prepared statement input parameters
                   while(rs.next())
                        for(int x=1; x<noOfColumns+1; x++)
                             setParameters(x, md.getColumnType(x));     
                        //Execute the prepared statement
                        checkForSuccess(ps.executeUpdate());                    
    //Here is the method it calls:
         private void setParameters(int columnNo, int dataType)
              lowLevel.info("Setting parameter number: " + columnNo);
              lowLevel.info("Data type:" + dataType);
              try
                   switch(dataType)
                        case Types.VARCHAR:
                             ps.setString(columnNo, rs.getString(columnNo)==null ? "" : rs.getString(columnNo).toUpperCase());
                             lowLevel.info("String set:" + rs.getString(columnNo));
                             break;
                        case Types.DECIMAL:
                             ps.setString(columnNo,  rs.getBigDecimal(columnNo)==null ? "0" : rs.getBigDecimal(columnNo).toString());
                             lowLevel.info("Decimal set");
                             break;
                        case Types.CHAR:
                             ps.setString(columnNo,  rs.getBigDecimal(columnNo)==null ? "0" : rs.getBigDecimal(columnNo).toString());
                             lowLevel.info("Char set");
                             break;
              catch (SQLException e)
                   lowLevel.warn("Error while setting parameters for " + dataType + " info");
                   e.printStackTrace();
         }

  • Executing Stored Procedure within Excel

    I am in the middle of setting up an Excel spreadsheet that will execute a stored procedure I have created and return the results to Excel. Pretty much following the example set here: 
    http://datapigtechnologies.com/blog/index.php/running-a-sql-stored-procedure-from-excel-with-dynamic-parameters/
    But, the problem I am stuck on and unable to yet find an answer to, is can I execute the procedure from within Excel and instead of specifying a parameter enter a WHERE clause. At the moment the last step of my stored procedure is:
    SELECT * FROM MY_TABLE
    WHERE ([PRODUCT] LIKE 'DESK-%') AND (NOT([DISCOUNT VALUE] IS NULL))
    But, I cannot find if it is possible to execute this from within Excel. I am not sure if it I am able to set the WHERE as a parameter which may be the way I should be going about this. 
    Thanks.

    Are you invoking a stored procedure, or are you sending a SELECT statement (ad-hoc query) to the SQL Server?  It seems like you are sending an ad-hoc query.
    If that is the case, I would not put the entire WHERE clause as a parameter. I would do it something like this:
    "SELECT * FROM MY_TABLE WHERE ([PRODUCT] LIKE '" & Range("B2").Value & "%') AND (NOT([DISCOUNT VALUE] IS NULL))"
    That assumes that the parameter that you want to use is in cell B2.
    Ideally, I would prefer not to use ad-hoc queries. Instead, create a stored procedure which takes the Product type as a parameter.  There are lots of examples on the net on how to query SQL Server from Excel via a stored procedure with parameters.

Maybe you are looking for