Help in stored procedure

i have a stored procedure in MSSQL which needs to be migrated to oracle 10g,i have got problem related to migration.
My mssql stored procedure is like as follows:
create procedure sample(
var1 varchar(20),
var2 varchar(20) )
as
declare @V_TBL table(col1 varchar(20), col2 varchar(20))
begin
insert into @V_TBL(col1,col2)
select col1,col2 from table1 where col1=@var1 and col2=@var2
some more logic
end
now in oracle how do i create this variable table or some other way is there to solve this?

> i have got problem related to migration.
Yep.. and this is to be expected. Why? Because Oracle is different than SQL-Server. And it is because of these differences that the market buys Oracle. Not because Oracle is the same as SQL-Server, but because it is difference.
The first thing you need to accept that migration is not going to be easy and painless - because of these differences.
What works and works well in SQL-Server, can spell a performance disaster in Oracle. And vice versa.
Why are temp tables typically used in SQL-Server and Sybase and Ingres and others? Because these databases have a different concurrency and isolation model than Oracle.
In these products, Writers can block Readers and Readers can block Writers.
In Oracle, a Reader will never block a Writer. A Writer will never block a Reader. One Writer will only ever block another Writer when vying for the same row. (and on a very rare occasion, when vying for the same data block that lacks sufficient transaction slots)
Simple example. I open a cursor [SELECT * FROM emp]. I fetch 10 rows of a 100 rows. You start a transaction. You issue a [DELETE FROM emp] and commit. The EMP table is now empty. I fetch the next set of 10 rows using my cursor. What do I see?
I see the next 10 rows as the EMP table looked like at the time I opened my cursor. I still see all 100 rows. Because that was The Truth at the time I opened my cursor. Oracle guarantees me a consistent read. No dirty reads.
So the "tricks" you pulled in SQL-Server to work around the reader and writer blocking issue (a failure of SQL-Server ito providing read consistency), is not applicable in Oracle. And the reasons and methods for using temp tables in SQL-Server is not valid in Oracle.
So when migrating SQL-Server stored proc code to Oracle.. it is a migration. Which means refactoring design and code. Do not expect to be able to simply port the design or code.

Similar Messages

  • Please help in Stored procedure? Psoting third time Urgent!!!

    Hi,
    We are running websphere3.5.3 on AS/400 machine with DB2Connect as local database.
    I am using com.ibm.db2.jdbc.app.DB2Driver
    We are trying to execute a servlet with stroedprocedure in it.
    In the bottom, I included complete error. Can some one help me? I tried so many things but nothing is working. Infact I could execute other storedprocedure which have hard code input values and outputvalues.
    Same stored procedure is working fine in coldfusion
    Following is creation, code, complete error of storedprocedure.
    I greatly appreciate your help.
    Thanks
    How we created stored procedure is
    create procedure fmgdata.test1
    in puserid char(10), in psuppno dec(7,0),in pitemno dec(5,0),out pmean dec(15,5),out pmedian dec(7,2), out
    pmode dec(7,2), out psamplefx dec(5,0), out pfmgdeal dec(7,2), out pfmgfist dec(7,2),out wrkdatmdy1 char(8),
    out wrkdatmdy2 char(8)
    language rpgle
    NOT DETERMINISTIC
    EXTERNAL NAME fmgdata.rdg002cf
    My code:
    public class storedProcServlet extends HttpServlet
    * Handle the GET Method
    public void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    PrintWriter output;
    String title = "Test Servlet2";
    // set the content type
    resp.setContentType("text/html");
    // write the output
    output = resp.getWriter();
    HttpSession session = req.getSession(true);
    output.println("<HTML><HEAD><TITLE>");
    output.println(title);
    output.println("</TITLE></HEAD><BODY>");
    // load the Db2driver bridge by referencing it
    try
    Class.forName("com.ibm.db2.jdbc.app.DB2Driver");
    catch (Exception e)
    output.println("<P>Failed to load DB2driver.");
    return;
    output.println("<P>Loaded DB2driver.");
    String url = "jdbc:db2://s105k4tm//FMGDATA//SYSDATA//FMGLIB//SYSLIB//*USRLBL//QSYS//aaa";
    // get a connection
    try
    CallableStatement cstmt = null;
    ResultSet resultset = null;
    Connection con = DriverManager.getConnection(
    url, "QSECOFR", "wasadmin"); // User Name: sa, Password: "
    cstmt = con.prepareCall ("{call FMGDATA.test1(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}");
    if(cstmt == null)
    output.println("problem while callable statement");
    else
    output.println("create callable statement is Ok");
    output.println("Before 1");
    cstmt.setString(1,"MILAR");
    output.println("Before 2");
    cstmt.setDouble(2,21000);
    output.println("Before 3");
    cstmt.setDouble(3,65886);
    output.println("Before 4");
    cstmt.registerOutParameter(4, java.sql.Types.DOUBLE);
    output.println("Before 5");
    cstmt.registerOutParameter(5, java.sql.Types.DOUBLE);
    output.println("Before 6");
    cstmt.registerOutParameter(6, java.sql.Types.DOUBLE);
    output.println("Before 7");
    cstmt.registerOutParameter(7, java.sql.Types.DOUBLE);
    output.println("Before 8");
    cstmt.registerOutParameter(8, java.sql.Types.DOUBLE);
    output.println("Before 9");
    cstmt.registerOutParameter(9, java.sql.Types.DOUBLE);
    output.println("Before 10");
    cstmt.registerOutParameter(10, java.sql.Types.CHAR);
    output.println("Before 11");
    cstmt.registerOutParameter(11, java.sql.Types.CHAR);
    output.println("After 11");
    output.println("Before execute");
    cstmt.execute();
    output.println("After execute");
    catch (Exception e)
    e.printStackTrace(output);
    output.println("<P>This is output from a Stored Procedure Servlet.");
    output.println("</BODY></HTML>");
    output.close();
    //Handle the POST method. To handle POST, we will simple pass the request to the GET method
    public void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    doGet(req,resp);
    error
    Loaded DB2driver.
    create callable statement is Ok
    Before 1 Before 2 Before 3 Before 4 Before 5 Before 6 Before 7 Before 8 Before 9 Before 10 Before 11 After 11 Before execute
    com.ibm.db2.jdbc.app.DB2SQLException2: Trigger program or external routine detected an error. java/lang/Throwable.(Ljava/lang/String;)V+4 (Throwable.java:94) java/sql/SQLException.(Ljava/lang/String;Ljava/lang/String;I)V+1 (SQLException.java:43) com/ibm/db2/jdbc/app/DB2SQLException2.(Ljava/lang/String;Ljava/lang/String;I)V+1 (DB2SQLException2.java:300) com/ibm/db2/jdbc/app/DB2PreparedStatementRuntimeImpl.execute(II)I+40 (DB2PreparedStatementRuntimeImpl.java:387) com/ibm/db2/jdbc/app/DB2PreparedStatement.execute()Z+28 (DB2PreparedStatement.java:1381) storedProcServlet.doGet(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V+0 (storedProcServlet.java:19) javax/servlet/http/HttpServlet.service(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V+32 (HttpServlet.java:740) javax/servlet/http/HttpServlet.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V+25 (HttpServlet.java:853) com/ibm/servlet/engine/webapp/StrictServletInstance.doService(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V+21 (ServletManager.java:626) com/ibm/servlet/engine/webapp/StrictLifecycleServlet._service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V+46 (StrictLifecycleServlet.java:160) com/ibm/servlet/engine/webapp/ServletInstance.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;Lcom/ibm/servlet/engine/webapp/WebAppServletInvocationEvent;)V+186 (ServletManager.java:360) com/ibm/servlet/engine/webapp/WebAppRequestDispatcher.handleWebAppDispatch(Lcom/ibm/servlet/engine/webapp/WebAppRequest;Ljavax/servlet/http/HttpServletResponse;Z)V+771 (WebAppRequestDispatcher.java:404) com/ibm/servlet/engine/webapp/WebAppRequestDispatcher.dispatch(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;Z)V+443 (WebAppRequestDispatcher.java:203) com/ibm/servlet/engine/webapp/WebAppRequestDispatcher.forward(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V+105 (WebAppRequestDispatcher.java:107) com/ibm/servlet/engine/srt/WebAppInvoker.handleInvocationHook(Ljava/lang/Object;)V+127 (WebAppInvoker.java:77) com/ibm/servlet/engine/invocation/CachedInvocation.handleInvocation(Ljava/lang/Object;)V+25 (CachedInvocation.java:67) com/ibm/servlet/engine/srp/ServletRequestProcessor.dispatchByURI(Ljava/lang/String;Lcom/ibm/servlet/engine/srp/ISRPConnection;)V+839 (ServletRequestProcessor.java:155) com/ibm/servlet/engine/oselistener/OSEListenerDispatcher.service(Lcom/ibm/servlet/engine/oselistener/api/IOSEConnection;)V+95 (OSEListener.java:300) com/ibm/servlet/engine/oselistener/SQEventListenerImp$ServiceRunnable.run()V+155 (SQEventListenerImp.java:230) com/ibm/servlet/engine/oselistener/SQEventListenerImp.notifySQEvent(Lcom/ibm/servlet/engine/oselistener/api/ISQEvent;)V+184 (SQEventListenerImp.java:104) com/ibm/servlet/engine/oselistener/serverqueue/SQEventSource.notifyEvent(Lcom/ibm/servlet/engine/oselistener/api/SQEventImp;)V+40 (SQEventSource.java:212) com/ibm/servlet/engine/oselistener/serverqueue/SQWrapperEventSource$SelectRunnable.notifyService()V+116 (SQWrapperEventSource.java:353) com/ibm/servlet/engine/oselistener/serverqueue/SQWrapperEventSource$SelectRunnable.run()V+124 (SQWrapperEventSource.java:220) com/ibm/servlet/engine/oselistener/outofproc/OutOfProcThread$CtlRunnable.run()V+104 (OutOfProcThread.java:248) java/lang/Thread.run()V+11 (Thread.java:479)
    This is output from a Stored Procedure Servlet.

    Thanks again Jschell,
    I will try to find out exactly what that stored proc is doing. They are saying this stored proc simply gets the values from database using inputs. No insert, delete or update.
    I am too thinking that sending inputs is giving problems.
    If you have any idea how can i format the inputs please let me know. Do you think any problem with driver??
    I did know the same is working in cold fusion fine. Basically it takes three values as inputs and gives 8 out put vaues. In cold fusion they formatted input such that
    AS/400 can under stand.
    In Cold Fusion they formatted as follows,
    <cfset supplier = Numberformat(supplier,'0000000')>
    <cfset item = Numberformat(item,'00000')>
    Even I am trying to do the same thing. It didn't work.
    I did execute some other simple sps where i give hard coded string as input retrieve int, double, strings as outputs.
    This is how they execute the same in cold fusion
    <cfstoredproc procedure="test1" datasource="#datasource#">          
    <cfprocparam type="In" cfsqltype="CF_SQL_CHAR" variable="puserid" value="#session.fsuser#">
    <cfprocparam type="In" cfsqltype="CF_SQL_INTEGER" variable="psuppno" value="#supplier#">
    <cfprocparam type="In" cfsqltype="CF_SQL_INTEGER" variable="pitemno" value="#item#">
    <cfprocparam type="Out" cfsqltype="CF_SQL_FLOAT" variable="pMean">
         <cfprocparam type="Out" cfsqltype="CF_SQL_FLOAT" variable="pMedian">
              <cfprocparam type="Out" cfsqltype="CF_SQL_FLOAT" variable="pMode">
              <cfprocparam type="Out" cfsqltype="CF_SQL_INTEGER" variable="psamplefx">
              <cfprocparam type="Out" cfsqltype="CF_SQL_FLOAT" variable="pfmgdeal">
              <cfprocparam type="Out" cfsqltype="CF_SQL_FLOAT" variable="pfmgfist">
              <cfprocparam type="Out" cfsqltype="CF_SQL_CHAR" variable="wrkdatmdy1">
              <cfprocparam type="Out" cfsqltype="CF_SQL_CHAR" variable="wrkdatmdy2">          
         </cfstoredproc>
    Thanks for any help,

  • Help: Using stored procedure to add new record in DB

    I am using stored procedures for a form. In DB, I have select and update procedures work without problems. However, for the insert procedure, it does not seem work right. Here is how things work for the insert procedure:
    1. On the form, I have an add record button, when this button is pressed, it calls the trigger "KEY_CREREC" with "create_record."
    2. A blank record is then shown on form. I then put in some test date. Apparently, this will cause "SYSTEM.STATUS" set to "CHANGED." when calling for commit, it only calls the DB update procedure.
    My question is how to make it call the insert procedure.
    Any suggestions are greatly appreciated.

    I just added to lines in key_commit to check the system.form_status:
    set_alert_property('AL_STOP', alert_message_text,'System Status: '||:system.form_status);
    al_button := show_alert('AL_STOP');
    After do_key('create_record') and some changes in fields, the :system.form_status shows "CHANGED.'
    Just wondering what will make the auto generated insert_procedure for the block to trigger. So far, no problems to do query and update with the DB stored procedure, but the insert does not seem working.
    Any help is greatly appreciated.
    P.S. The new post might be more clear:
    http://forums.oracle.com/forums/thread.jspa?threadID=675578&tstart=0
    Message was edited by:
    WJH

  • Need a help on stored procedure

    I have the sample data like the below.
    Employee Id Key Value
    1 Name Joe
    1 Age 28
    1 Addr Houston
    1 Sex M
         2 Addr Chicago     
    I need to get a result somethin like the below using a stored procedure.
    ID Name Age Addr Sex
    1 Jose 28 Houston M
    2     null     null     Chicago     null
    I need to write a stored proc for this......

    Assuming list of keys is static:
    with t as (
               select 1 employee_id,'Name' key,'Joe' val from dual union all
               select 1,'Age','28' from dual union all
               select 1,'Addr','Houston' from dual union all
               select 1,'Sex','M' from dual union all
               select 2,'Addr','Chicago' from dual
    select  employee_id,
            min(case key when 'Name' then val end) name,
            min(case key when 'Age' then val end) age,
            min(case key when 'Addr' then val end) addr,
            min(case key when 'Sex' then val end) sex
      from  t
      group by employee_id
      order by employee_id
    EMPLOYEE_ID NAME                                AGE     ADDR    SEX
              1 Joe                                 28      Houston M
              2                                             Chicago
    SQL> SY.

  • Help on Stored Procedure!

    Hi,
    I've this table AFM_USERS.
    CREATE TABLE AFM_USERS
    USER_PWD VARCHAR2(64 BYTE),
    USER_NAME VARCHAR2(64 BYTE),
    BAD_LOGIN NUMBER DEFAULT 0
    USER_NAME.......USER_PSWD........COUNTER
    ADAMS.............ADAMS$............0
    JOHN..............JOHN$.............0
    SMITH.............SMITH$............0
    KOSTER............KOSTER$...........0
    I've my application that connect Oracle via ODBC.
    When I connect, for example, with USER_NAME=ADAMS PASSWORD=ADAMS$ into sys.fga_log$ table I get 2 records:
    OSUID.................OSHST......OBJ$SCHEMA....OBJ$NAME.....POLICYNAME.......TIMESTAMP..............LSQLTEXT...............................................................LSQLBIND
    191.164.2.34\Sam...191.164.2.34...AFM_SECURE....AFM_USERS....AFM_LOGIN..01/12/2008 7:15:23,7030..SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):ADAMS
    191.164.2.34\Sam...191.164.2.34.....AFM........AFM_MODS....AFM_MODS.....01/12/2008 7:15:26,7044....SELECT afm_module,button,afm_module_it FROM afm_mods.................................
    When I connect, for example, with USER_NAME=SMITH PASSWORD=SMITH$ into sys.fga_log$ table I get others 2 records:
    OSUID.................OSHST......OBJ$SCHEMA....OBJ$NAME.....POLICYNAME.....TIMESTAMP..............LSQLTEXT...............................................................LSQLBIND
    191.164.2.34\Sam...191.164.2.34....AFM_SECURE....AFM_USERS....AFM_LOGIN..01/12/2008 7:15:23,7030..SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):ADAMS
    191.164.2.34\Sam...191.164.2.34....AFM........AFM_MODS.......AFM_MODS....01/12/2008 7:15:26,7044....SELECT afm_module,button,afm_module_it FROM afm_mods.................................
    191.164.2.34\Sam...191.164.2.34...AFM_SECURE....AFM_USERS....AFM_LOGIN....01/12/2008 7:15:35,7070...SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):SMITH
    191.164.2.34\Sam...191.164.2.34....AFM........AFM_MODS......AFM_MODS....01/12/2008 7:15:38,7067.....SELECT afm_module,button,afm_module_it FROM afm_mods.................................
    When I connect, for example, with USER_NAME=SMITH PASSWORD=AAAA(Bad Password) into sys.fga_log$ table I get just one record:
    OSUID.................OSHST......OBJ$SCHEMA....OBJ$NAME.....POLICYNAME.....TIMESTAMP..............LSQLTEXT...............................................................LSQLBIND
    191.164.2.34\Sam...191.164.2.34....AFM_SECURE....AFM_USERS....AFM_LOGIN..01/12/2008 7:15:23,7030..SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):ADAMS
    191.164.2.34\Sam...191.164.2.34....AFM........AFM_MODS.......AFM_MODS....01/12/2008 7:15:26,7044....SELECT afm_module,button,afm_module_it FROM afm_mods.................................
    191.164.2.34\Sam...191.164.2.34...AFM_SECURE....AFM_USERS....AFM_LOGIN....01/12/2008 7:15:35,7070...SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):SMITH
    191.164.2.34\Sam...191.164.2.34....AFM........AFM_MODS......AFM_MODS....01/12/2008 7:15:38,7067.....SELECT afm_module,button,afm_module_it FROM afm_mods.................................
    191.164.2.34\Sam...191.164.2.34....AFM_SECURE....AFM_USERS....AFM_LOGIN..01/12/2008 7:16:01,7067.......SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):SMITH
    When I connect, for example, with USER_NAME=KOSTER PASSWORD=BBBBB(Bad Password) into sys.fga_log$ table I get just one record:
    OSUID.................OSHST......OBJ$SCHEMA....OBJ$NAME.....POLICYNAME.....TIMESTAMP..............LSQLTEXT...............................................................LSQLBIND
    191.164.2.34\Sam...191.164.2.34....AFM_SECURE....AFM_USERS....AFM_LOGIN..01/12/2008 7:15:23,7030..SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):ADAMS
    191.164.2.34\Sam...191.164.2.34....AFM........AFM_MODS.......AFM_MODS....01/12/2008 7:15:26,7044....SELECT afm_module,button,afm_module_it FROM afm_mods.................................
    191.164.2.34\Sam...191.164.2.34...AFM_SECURE....AFM_USERS....AFM_LOGIN....01/12/2008 7:15:35,7070...SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):SMITH
    191.164.2.34\Sam...191.164.2.34....AFM........AFM_MODS......AFM_MODS....01/12/2008 7:15:38,7067.....SELECT afm_module,button,afm_module_it FROM afm_mods.................................
    191.164.2.34\Sam...191.164.2.34....AFM_SECURE....AFM_USERS....AFM_LOGIN..01/12/2008 7:16:01,7067.......SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):SMITH
    191.164.2.34\Sam...191.164.2.34....AFM_SECURE....AFM_USERS....AFM_LOGIN...01/12/2008 7:17:04,7067.......SELECT USER_NAME,USER_PSWD, COUNTER FROM afm_users WHERE user_name=:1....#1(5):KOSTER
    Now I'd like to create a stored procedure on sys.fga_log$ table that increase or decrease of 1 the COUNTER column of table AFM_USERS with these conditions:
    if I connect not correctly (user o password incorrect) I increase COUNTER of 1 (+1)
    if I connect correctly (user and password correct) I decrease COUNTER of 1 (-1)
    In my case I'd like to get like this:
    When I connect with USER_NAME=ADAMS PASSWORD=ADAMS$ I'd like to get:
    execute my_stored_procedure;
    select *
    from AFM_USERS;
    USER_NAME.......USER_PSWD........COUNTER
    ADAMS.............ADAMS$...............-1 -- (-1)
    JOHN..............JOHN$...................0
    SMITH.............SMITH$.................0
    KOSTER............KOSTER$.............0
    When I connect with USER_NAME=SMITH PASSWORD=SMITH$ I'd like to get:
    execute my_stored_procedure;
    select *
    from AFM_USERS;
    USER_NAME.......USER_PSWD........COUNTER
    ADAMS.............ADAMS$............-1
    JOHN..............JOHN$.................0
    SMITH.............SMITH$..............-1 -- (-1)
    KOSTER............KOSTER$...........0
    When I connect with USER_NAME=SMITH PASSWORD=AAAA(Bad Password) I'd like to get:
    execute my_stored_procedure;
    select *
    from AFM_USERS;
    USER_NAME.......USER_PSWD........COUNTER
    ADAMS.............ADAMS$............-1
    JOHN..............JOHN$.................0
    SMITH.............SMITH$...............0 -- (+1)
    KOSTER............KOSTER$............0
    When I connect with USER_NAME=SMITH PASSWORD=BBBBB(Bad Password) I'd like to get:
    execute my_stored_procedure;
    select *
    from AFM_USERS;
    USER_NAME.......USER_PSWD........COUNTER
    ADAMS.............ADAMS$............-1
    JOHN..............JOHN$.................0
    SMITH.............SMITH$...............1 -- (+1)
    KOSTER............KOSTER$...........0
    When I connect with USER_NAME=KOSTER PASSWORD=BBBBB(Bad Password) I'd like to get:
    execute my_stored_procedure;
    select *
    from AFM_USERS;
    USER_NAME.......USER_PSWD........COUNTER
    ADAMS.............ADAMS$..............-1
    JOHN..............JOHN$...................0
    SMITH.............SMITH$.................1
    KOSTER............KOSTER$..............1 -- (+1)
    How can I create my stored procedure?
    Thanks in advance.

    Raf Royal wrote:
    Hi,
    I've this table AFM_USERS.You do but we can't see them very well.
    After more than 250 posts on the forum we would expect you to be able to format any code and data on your posts you make here, rather than attempting to pad them out with lots of full-stops..............
    Edit your post and re-post the code/data with {noformat}{noformat} tags around it so that it's readable.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help in Stored Procedure Required

    Dear All,
    I have an udf in my Sales Order u_EnqNo which has some numbers. I want to have a check if while booking the Sales Order if some particular numbers are there then in the project code field which is in the row level of Sales Order should have project code ending with SP ( Special Project).
    I am trying to make an Stored Procedure but its somehow not working and been asking for SP when already SP is there.
    --Project code for Sales Order - Special Projects
    if  @transaction_type IN (N'A', N'U') AND (@Object_type IN ('17'))
    begin
    if exists (select * from rdr1 b,ordr a
    where b.DocEntry=@list_of_cols_val_tab_del
    and (b.Project is null or b.Project='' or b.Project NOT Like '%%_SP' and a.DocEntry=b.Docentry
    and a.u_EnqNo ='95021729' or a.u_EnqNo ='95021970' or a.u_EnqNo ='95022171' or
    a.u_EnqNo ='95021972' or a.u_EnqNo ='95022210' or a.u_EnqNo ='95017240' or
    a.u_EnqNo ='95010501' or a.u_EnqNo ='95021280' or a.u_EnqNo ='95020277' or
    a.u_EnqNo ='95021957' or a.u_EnqNo ='95017862' or a.u_EnqNo ='95021093' or
    a.u_EnqNo ='95020915' or a.u_EnqNo ='95021907' or a.u_EnqNo ='95015477' or
    a.u_EnqNo ='95100300' or a.u_EnqNo ='95100354' or a.u_EnqNo ='95100349' or
    a.u_EnqNo ='95100350' or a.u_EnqNo ='95028879' or a.u_EnqNo ='95021454' or
    a.u_EnqNo ='95100350' or a.u_EnqNo ='95028879' or a.u_EnqNo ='95021454' or
    a.u_EnqNo ='95021666' or a.u_EnqNo ='95021519' or a.u_EnqNo ='95022148'))
    begin
    select  @error=10 , @error_message = N' Special Project...Provide Special Project Code with Suffix as SP'
    end
    end
    Kindly advise.
    Regards,
    Swamy

    You did not consider the precedence of the logical operators!
    Try this:
    --Project code for Sales Order - Special Projects
    if  @transaction_type IN (N'A', N'U') AND (@Object_type IN ('17'))
    begin
    if exists (select * from rdr1 b,ordr a
    where b.DocEntry=@list_of_cols_val_tab_del
    and (b.Project is null or b.Project='' or b.Project NOT Like '%%_SP' and a.DocEntry=b.Docentry
    and
    (a.u_EnqNo ='95021729' or a.u_EnqNo ='95021970' or a.u_EnqNo ='95022171' or
    a.u_EnqNo ='95021972' or a.u_EnqNo ='95022210' or a.u_EnqNo ='95017240' or
    a.u_EnqNo ='95010501' or a.u_EnqNo ='95021280' or a.u_EnqNo ='95020277' or
    a.u_EnqNo ='95021957' or a.u_EnqNo ='95017862' or a.u_EnqNo ='95021093' or
    a.u_EnqNo ='95020915' or a.u_EnqNo ='95021907' or a.u_EnqNo ='95015477' or
    a.u_EnqNo ='95100300' or a.u_EnqNo ='95100354' or a.u_EnqNo ='95100349' or
    a.u_EnqNo ='95100350' or a.u_EnqNo ='95028879' or a.u_EnqNo ='95021454' or
    a.u_EnqNo ='95100350' or a.u_EnqNo ='95028879' or a.u_EnqNo ='95021454' or
    a.u_EnqNo ='95021666' or a.u_EnqNo ='95021519' or a.u_EnqNo ='95022148'
    begin
    select  @error=10 , @error_message = N' Special Project...Provide Special Project Code with Suffix as SP'
    end
    end
    Or you can use a more simple form using this:
    a.u_EnqNo in ('95021729', . . ., '95022148')

  • Urgent Help on Stored Procedure

    Hi,
    Could any one pls help me?
    The following is a stored proc where I'm trying to upload data from different tables into one single table. Queries #1 & #3[within cursor loop] are giving results for each policy nbr but #2 is returning no row which is correct in some occassion. I want the proc to go ahead and insert null values or Zero(either is O.K.) for #2 for all existing values of #1 & #3 for all policy numbers. But the proc is not proceeding further for other policy numbers as soon as it gets no value from #2 for the first policy number. It stops reading cursor for subsequent policy numbers and does no insert into the extract_rpts table. I'm using EXCEPTION handling but not working.
    Regards,
    Manojit.
    CREATE OR REPLACE PROCEDURE proc_upload_extract_data IS
    lv_POLICYNO extract_rpts.POLICYNO%TYPE;
    lv_ORIG_CONTR_CNT extract_rpts.ORIG_CONTR_CNT%TYPE :=0;
    lv_ANN_PMT_SUM_CNT extract_rpts.ANN_PMT_SUM_CNT%TYPE :=0;
    lv_ANN_GROSS_PMT_SUM_VAL extract_rpts.ANN_GROSS_PMT_SUM_VAL :=0;
    lv_stat varchar2(100);
    BEGIN
    /* Get all policy nbrs. */
    DECLARE CURSOR extr_pol IS
    SELECT DISTINCT policyno FROM master1;
    /* Following name will be referred for the cursor */
    get_pol extr_pol%ROWTYPE;
    /* Get all policy numbers from the cursor before extracting report data
    for each of the policies*/
    BEGIN
    OPEN extr_pol;
    LOOP
    FETCH extr_pol INTO get_pol;
    EXIT WHEN extr_pol%NOTFOUND;
    lv_POLICYNO := get_pol.policyno;
    /* 1. Original Contract Number */
    select count(policyno)
    into lv_ORIG_CONTR_CNT
    from master1
    where policyno = lv_POLICYNO
    group by policyno;
    /* 2. Annuity Payment Summation Count */
    select count(trxcode)
    into lv_ANN_PMT_SUM_CNT
    from master3
    where trxcode = 7 and
    policyno = lv_POLICYNO
    group by policyno;
    /* 3. Annuity-Gross Payment Summation Value */
    select sum(d.grosspay)
    into lv_ANN_GROSS_PMT_SUM_VAL
    from master3 c, master4 d
    where c.policyno = lv_POLICYNO and
    c.trxcode = 7 and
    c.policyno = d.policyno and
    c.DATETRXEFF = d.DATETPAY
    group by c.policyno;
    /* Now since the data for the policy number is loaded into local
    variables, it is inserted into the extract_rpts table */
    insert into extract_rpts
    POLICYNO,
    ORIG_CONTR_CNT,
    ANN_PMT_SUM_CNT,
    ANN_GROSS_PMT_SUM_VAL )
    values (
    lv_POLICYNO,
    lv_ORIG_CONTR_CNT,
    lv_ANN_PMT_SUM_CNT,
    lv_ANN_GROSS_PMT_SUM_VAL
    END LOOP; /* for the cursor extr_pol */
    CLOSE extr_pol;
    END;
    EXCEPTION
    WHEN OTHERS THEN
    lv_stat := 'Correct Record';
    commit;
    END; /* of the procedure proc_upload_extract_data */
    null

    Hi Manojit,
    Unfortunatly your question is not
    related to Oracle Spatial.
    Please try posting this to metalink.
    Thanks.
    Dan

  • Need help with BC4J/Struts application using a Stored Procedure

    Hi,
    I am doing a proof of concept for a new project using JDeveloper, Struts and BC4J. We want to reuse our Business logic that is currently residing in Oracle Stored Procedures. I previously created a BC4J Entity Object based on a stored procedure Using Oracle Stored Procedures but this stored procedure is a bit different in that it returns a ref cursor as one of the paramters. http://radio.weblogs.com/0118231/stories/2003/03/03/gettingAViewObjectsResultRowsFromARefCursor.html
    I tried the above method, but I am having some trouble with it. I keep getting the error ORA-01008: not all variables are bound when I test it using the AppModule tester.
    Here is the store procedure definition:
    CREATE OR REPLACE PACKAGE pprs_test_wrappers IS
    TYPE sn_srch_results IS REF CURSOR;
    PROCEDURE sn_srch_main_test
    (serial_num_in IN OUT VARCHAR2
    ,serial_coll_cd_in IN OUT NUMBER
    ,max_rows_allowed IN OUT NUMBER
    ,total_rows_selected IN OUT NUMBER
    ,message_cd_out IN OUT VARCHAR2
    ,query_results          OUT sn_srch_results
    END pprs_test_wrappers;
    And here is my code:
    package pprs;
    import java.math.BigDecimal;
    import java.sql.CallableStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.sql.Types;
    import oracle.jbo.JboException;
    import oracle.jbo.domain.Number;
    import oracle.jbo.server.DBTransaction;
    import oracle.jbo.server.ViewObjectImpl;
    import oracle.jbo.server.ViewRowImpl;
    import oracle.jbo.server.ViewRowSetImpl;
    import oracle.jdbc.driver.OracleCallableStatement;
    import oracle.jdbc.driver.OracleTypes;
    // --- File generated by Oracle Business Components for Java.
    public class LienCheckImpl extends ViewObjectImpl
    * This is the PLSQL block that we will execute to retrieve the REF CURSOR
    private static final String SQL =
    "begin ? := pprs_test_wrappers.sn_srch_main_test(?, ?, ?, ?, ?, ?);end;";
    public LienCheckImpl() {}
    * Overridden framework method.
    * Executed when the framework needs to issue the database query for
    * the query collection based on this view object. One view object
    * can produce many related result sets, each potentially the result
    * of different bind variable values. If the rowset in query is involved
    * in a framework-coordinated master/detail viewlink, then the params array
    * will contain one or more framework-supplied bind parameters. If there
    * are any user-supplied bind parameter values, they will PRECEED the
    * framework-supplied bind variable values in the params array, and the
    * number of user parameters will be indicated by the value of the
    * numUserParams argument.
    protected void executeQueryForCollection(Object qc,Object[] params,int numUserParams) {
    * If there are where-clause params (for example due to a view link)
    * they will be in the 'params' array.
    * We assume that if some parameter is present, that it is a Deptno
    * value to pass as an argument to the stored procedure.
    * NOTE: Due to Bug#2828248 I have to cast to BigDecimal for now,
    * ---- but this parameter value should be oracle.jbo.domain.Number type.
    String serialNumIn = null;
    BigDecimal serialCollCdIn = null;
    BigDecimal maxRowsAllowed = null;
    BigDecimal totalRowsSelected = null;
    String messageCdOut = null;
    if (params != null) {
    serialNumIn = (String)params[0];
    serialCollCdIn = (BigDecimal)params[1];
    maxRowsAllowed = (BigDecimal)params[2];
    totalRowsSelected = (BigDecimal)params[3];
    messageCdOut = (String)params[4];
    storeNewResultSet(qc,retrieveRefCursor(qc,serialNumIn,
    serialCollCdIn,
    maxRowsAllowed,
    totalRowsSelected,
    messageCdOut));
    super.executeQueryForCollection(qc, params, numUserParams);
    * Overridden framework method.
    * Wipe out all traces of a built-in query for this VO
    protected void create() {
    getViewDef().setQuery(null);
    getViewDef().setSelectClause(null);
    setQuery(null);
    * Overridden framework method.
    * The role of this method is to "fetch", populate, and return a single row
    * from the datasource by calling createNewRowForCollection() and populating
    * its attributes using populateAttributeForRow().
    protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {
    * We ignore the JDBC ResultSet passed by the framework (null anyway) and
    * use the resultset that we've stored in the query-collection-private
    * user data storage
    rs = getResultSet(qc);
    * Create a new row to populate
    ViewRowImpl r = createNewRowForCollection(qc);
    try {
    * Populate new row by attribute slot number for current row in Result Set
    populateAttributeForRow(r,0, nullOrNewNumber(rs.getBigDecimal(1)));
    populateAttributeForRow(r,1, nullOrNewNumber(rs.getBigDecimal(2)));
    populateAttributeForRow(r,2, rs.getString(3));
    populateAttributeForRow(r,3, rs.getString(4));
    populateAttributeForRow(r,4, rs.getString(5));
    catch (SQLException s) {
    throw new JboException(s);
    return r;
    * Overridden framework method.
    * Return true if the datasource has at least one more record to fetch.
    protected boolean hasNextForCollection(Object qc) {
    ResultSet rs = getResultSet(qc);
    boolean nextOne = false;
    try {
    nextOne = rs.next();
    * When were at the end of the result set, mark the query collection
    * as "FetchComplete".
    if (!nextOne) {
    setFetchCompleteForCollection(qc, true);
    * Close the result set, we're done with it
    rs.close();
    catch (SQLException s) {
    throw new JboException(s);
    return nextOne;
    * Overridden framework method.
    * The framework gives us a chance to clean up any resources related
    * to the datasource when a query collection is done being used.
    protected void releaseUserDataForCollection(Object qc, Object rs) {
    * Ignore the ResultSet passed in since we've created our own.
    * Fetch the ResultSet from the User-Data context instead
    ResultSet userDataRS = getResultSet(qc);
    if (userDataRS != null) {
    try {
    userDataRS.close();
    catch (SQLException s) {
    /* Ignore */
    super.releaseUserDataForCollection(qc, rs);
    * Return a JDBC ResultSet representing the REF CURSOR return
    * value from our stored package function.
    private ResultSet retrieveRefCursor(Object qc,
    String serialNum,
    BigDecimal serialColCd,
    BigDecimal maxRows,
    BigDecimal totalRows,
    String messageCd ) {
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement(SQL,DBTransaction.DEFAULT);
    * Register the first bind parameter as our return value of type CURSOR
    st.registerOutParameter(1,OracleTypes.CURSOR);
    * Set the value of the 2nd bind variable to pass id as argument
    if (serialNum == null) st.setNull(2,Types.CHAR);
    else st.setString(2,serialNum);
    if (serialColCd == null) st.setNull(3,Types.NUMERIC);
    else st.setBigDecimal(3,serialColCd);
    if (maxRows == null) st.setNull(4,Types.NUMERIC);
    else st.setBigDecimal(4,maxRows);
    if (totalRows == null) st.setNull(5,Types.NUMERIC);
    else st.setBigDecimal(5,totalRows);
    if (messageCd == null) st.setNull(6,Types.CHAR);
    else st.setString(6,messageCd);
    st.execute();
    ResultSet rs = ((OracleCallableStatement)st).getCursor(1);
    * Make this result set use the fetch size from our View Object settings
    rs.setFetchSize(getFetchSize());
    return rs ;
    catch (SQLException s) {
    throw new JboException(s);
    finally {try {st.close();} catch (SQLException s) {}}
    * Store a new result set in the query-collection-private user-data context
    private void storeNewResultSet(Object qc, ResultSet rs) {
    ResultSet existingRs = getResultSet(qc);
    // If this query collection is getting reused, close out any previous rowset
    if (existingRs != null) {
    try {existingRs.close();} catch (SQLException s) {}
    setUserDataForCollection(qc,rs);
    hasNextForCollection(qc); // Prime the pump with the first row.
    * Retrieve the result set wrapper from the query-collection user-data
    private ResultSet getResultSet(Object qc) {
    return (ResultSet)getUserDataForCollection(qc);
    * Return either null or a new oracle.jbo.domain.Number
    private static oracle.jbo.domain.Number nullOrNewNumber(BigDecimal b) {
    try {
    return b != null ? new oracle.jbo.domain.Number(b) : null;
    catch (SQLException s) { }
    return null;
    I created the view object in expert mode so there is no entity object. Can someone help? I don't have much time left to finish this.
    Also, could I have done this from the Entity object instead of the view object by registering the ref cursor OUT parameter in handleStoredProcInsert()?
    Thanks
    Natalie

    I was able to get the input parameter by putting the following in my struts actions class
    vo.setWhereClauseParam(0,request.getParameter("row0_SerialNum"));
    The full code is:
    package mypackage2;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import oracle.jbo.html.BC4JContext;
    import oracle.jbo.ViewObject;
    import oracle.jbo.html.struts11.BC4JUtils;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    public class LienCheckView1QueryAction extends Action
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    BC4JContext context = BC4JContext.getContext(request);
    // Retrieve the view object instance to work with by name
    ViewObject vo = context.getApplicationModule().findViewObject("LienCheckView1");
    vo.setRangeSize(3);
    vo.setIterMode(ViewObject.ITER_MODE_LAST_PAGE_PARTIAL);
    // Do any additional VO setup here (e.g. setting bind parameter values)
    vo.setWhereClauseParam(0,request.getParameter("row0_SerialNum"));
    // default value for serialCollCd 1 is for Motor Vehicles
    vo.setWhereClauseParam(1,new oracle.jbo.domain.Number(1));
    // Default value for maxRows_allowed
    vo.setWhereClauseParam(2,new oracle.jbo.domain.Number(20));
    return BC4JUtils.getForwardFromContext(context, mapping);
    This doesn't always work properly though. The first time I press the query button, the SerialNum parameter is still null, however if I re-execute the query by pressing the query button again. It will work, and return the rows. I always have to query twice. Also the SerialNum attribute is set to a String in my view object, it is a varchar column in the database, but some serial number I enter give a "Error Message: oracle.jbo.domain.Number ". This happens even though the underlying BC4J is returning values for the query. I also get a "500 Internal Server Error java.lang.ClassCastException: java.lang.String on my View object's code at line 65 which is
    if (params.length>1) serialCollCdIn = (BigDecimal)params[1];
    This is an input paramter to the oracle stored procedure that defaults to a Number value of 1.
    Any idea what the problem is? Here is the full code for my view object:
    package mypackage1;
    import java.math.BigDecimal;
    import java.sql.CallableStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.sql.Types;
    import oracle.jbo.JboException;
    import oracle.jbo.domain.Number;
    import oracle.jbo.server.DBTransaction;
    import oracle.jbo.server.ViewObjectImpl;
    import oracle.jbo.server.ViewRowImpl;
    import oracle.jbo.server.ViewRowSetImpl;
    import oracle.jdbc.driver.OracleCallableStatement;
    import oracle.jdbc.driver.OracleTypes;
    // --- File generated by Oracle Business Components for Java.
    public class LienCheckViewImpl extends ViewObjectImpl
    * This is the PLSQL block that we will execute to retrieve the REF CURSOR
    private static final String SQL =
    "begin pprs_test_wrappers.sn_srch_main_test(?, ?, ?, ?, ?, ?);end;";
    private BigDecimal totalRows = null;
    private String messageCd = null;
    private BigDecimal serialColCd = null;
    private BigDecimal maxRows = null;
    public LienCheckViewImpl() {}
    * Overridden framework method.
    * Executed when the framework needs to issue the database query for
    * the query collection based on this view object. One view object
    * can produce many related result sets, each potentially the result
    * of different bind variable values. If the rowset in query is involved
    * in a framework-coordinated master/detail viewlink, then the params array
    * will contain one or more framework-supplied bind parameters. If there
    * are any user-supplied bind parameter values, they will *PRECEED* the
    * framework-supplied bind variable values in the params array, and the
    * number of user parameters will be indicated by the value of the
    * numUserParams argument.
    protected void executeQueryForCollection(Object qc,Object[] params,int numUserParams) {
    * If there are where-clause params (for example due to a view link)
    * they will be in the 'params' array.
    * We assume that if some parameter is present, that it is a Deptno
    * value to pass as an argument to the stored procedure.
    * NOTE: Due to Bug#2828248 I have to cast to BigDecimal for now,
    * ---- but this parameter value should be oracle.jbo.domain.Number type.
    String serialNumIn = null;
    BigDecimal serialCollCdIn = null;
    BigDecimal maxRowsAllowed = null;
    BigDecimal totalRowsSelected = null;
    String messageCdOut = null;
    if (params != null) {
    if (params.length>0) serialNumIn = (String)params[0];
    if (params.length>1) serialCollCdIn = (BigDecimal)params[1];
    if (params.length>2) maxRowsAllowed = (BigDecimal)params[2];
    storeNewResultSet(qc,retrieveRefCursor(qc,serialNumIn,
    serialCollCdIn,
    maxRowsAllowed));
    super.executeQueryForCollection(qc, params, numUserParams);
    * Overridden framework method.
    * Wipe out all traces of a built-in query for this VO
    protected void create() {
    getViewDef().setQuery(null);
    getViewDef().setSelectClause(null);
    setQuery(null);
    * Overridden framework method.
    * The role of this method is to "fetch", populate, and return a single row
    * from the datasource by calling createNewRowForCollection() and populating
    * its attributes using populateAttributeForRow().
    protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {
    * We ignore the JDBC ResultSet passed by the framework (null anyway) and
    * use the resultset that we've stored in the query-collection-private
    * user data storage
    rs = getResultSet(qc);
    * Create a new row to populate
    ViewRowImpl r = createNewRowForCollection(qc);
    try {
    * Populate new row by attribute slot number for current row in Result Set
    //AddedByRegisNum
    populateAttributeForRow(r,0, nullOrNewNumber(rs.getBigDecimal(1)));
    System.out.println("AddedByRegisNum :" + rs.getBigDecimal(1));
    // OrigRegisNum
    populateAttributeForRow(r,1, nullOrNewNumber(rs.getBigDecimal(2)));
    System.out.println("OrigRegisNum :" + rs.getBigDecimal(2));
    // SerialNum
    populateAttributeForRow(r,2, rs.getString(3));
    System.out.println("SerialNum :" + rs.getString(3));
    // SerialNumDesc
    populateAttributeForRow(r,3, rs.getString(4));
    System.out.println("SerialNumDesc :" + rs.getString(4));
    // FlagExactMatch
    populateAttributeForRow(r,4, rs.getString(5));
    System.out.println("FlagExactMatch :" + rs.getString(5));
    // MessageCd
    populateAttributeForRow(r,5, messageCd);
    // TotalRows
    populateAttributeForRow(r,6, totalRows);
    catch (SQLException s) {
    throw new JboException(s);
    return r;
    * Overridden framework method.
    * Return true if the datasource has at least one more record to fetch.
    protected boolean hasNextForCollection(Object qc) {
    ResultSet rs = getResultSet(qc);
    boolean nextOne = false;
    try {
    nextOne = rs.next();
    * When were at the end of the result set, mark the query collection
    * as "FetchComplete".
    if (!nextOne) {
    setFetchCompleteForCollection(qc, true);
    * Close the result set, we're done with it
    rs.close();
    catch (SQLException s) {
    throw new JboException(s);
    return nextOne;
    * Overridden framework method.
    * The framework gives us a chance to clean up any resources related
    * to the datasource when a query collection is done being used.
    protected void releaseUserDataForCollection(Object qc, Object rs) {
    * Ignore the ResultSet passed in since we've created our own.
    * Fetch the ResultSet from the User-Data context instead
    ResultSet userDataRS = getResultSet(qc);
    if (userDataRS != null) {
    try {
    userDataRS.close();
    catch (SQLException s) {
    /* Ignore */
    super.releaseUserDataForCollection(qc, rs);
    * Overridden framework method
    * Return the number of rows that would be returned by executing
    * the query implied by the datasource. This gives the developer a
    * chance to perform a fast count of the rows that would be retrieved
    * if all rows were fetched from the database. In the default implementation
    * the framework will perform a SELECT COUNT(*) FROM (...) wrapper query
    * to let the database return the count. This count might only be an estimate
    * depending on how resource-intensive it would be to actually count the rows.
    public long getQueryHitCount(ViewRowSetImpl viewRowSet) {
    Object[] params = viewRowSet.getParameters(true);
    String serialNumIn = (String)params[0];
    BigDecimal serialCollCdIn = (BigDecimal)params[1];
    BigDecimal maxRowsAllowed = (BigDecimal)params[2];
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement(SQL,DBTransaction.DEFAULT);
    * Register the fourth bind parameter as our return value of type NUMERIC
    st.registerOutParameter(4,Types.NUMERIC);
    * Set the value of the 3 bind variables to pass as arguments
    if (serialNumIn == null) st.setNull(1, Types.CHAR);
    else st.setString(1,serialNumIn);
    if (serialCollCdIn == null) st.setNull(2,Types.NUMERIC);
    else st.setBigDecimal(2,serialCollCdIn);
    if (maxRowsAllowed == null) st.setNull(3, Types.NUMERIC);
    else st.setBigDecimal(3, maxRowsAllowed);
    st.execute();
    System.out.println("returning value of :" + st.getLong(4));
    return st.getLong(4);
    catch (SQLException s) {
    throw new JboException(s);
    finally {try {st.close();} catch (SQLException s) {}}
    * Return a JDBC ResultSet representing the REF CURSOR return
    * value from our stored package function.
    private ResultSet retrieveRefCursor(Object qc,
    String serialNum,
    BigDecimal serialColCd,
    BigDecimal maxRows) {
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement(SQL,DBTransaction.DEFAULT);
    * Set the value of the bind variables
    System.out.println("SerialNumIn :" + serialNum);
    if (serialNum == null) st.setNull(1,Types.CHAR);
    else st.setString(1,serialNum);
    if (serialColCd == null) st.setNull(2,Types.NUMERIC);
    else st.setBigDecimal(2,serialColCd);
    if (maxRows == null) st.setNull(3,Types.NUMERIC);
    else st.setBigDecimal(3,maxRows);
    st.registerOutParameter(1, Types.CHAR); // serialNum
    st.registerOutParameter(2, Types.NUMERIC); // serialColCd
    st.registerOutParameter(3, Types.NUMERIC); // maxRows
    st.registerOutParameter(4, Types.NUMERIC); // totalRows
    st.registerOutParameter(5, Types.CHAR); // messageCd
    * Register the 6th bind parameter as our return value of type CURSOR
    st.registerOutParameter(6,OracleTypes.CURSOR);
    st.execute();
    ResultSet rs = ((OracleCallableStatement)st).getCursor(6);
    serialColCd = st.getBigDecimal(2);
    System.out.println("SerialColCd= " + serialColCd);
    maxRows = st.getBigDecimal(3);
    System.out.println("maxRows= " + maxRows);
    totalRows = st.getBigDecimal(4);
    System.out.println("totalRows= " + totalRows);
    messageCd = st.getString(5);
    System.out.println("messageCd= " + messageCd);
    * Make this result set use the fetch size from our View Object settings
    rs.setFetchSize(getFetchSize());
    return rs ;
    catch (SQLException s) {
    throw new JboException(s);
    finally {try {st.close();} catch (SQLException s) {}}
    * Store a new result set in the query-collection-private user-data context
    private void storeNewResultSet(Object qc, ResultSet rs) {
    ResultSet existingRs = getResultSet(qc);
    // If this query collection is getting reused, close out any previous rowset
    if (existingRs != null) {
    try {existingRs.close();} catch (SQLException s) {}
    setUserDataForCollection(qc,rs);
    hasNextForCollection(qc); // Prime the pump with the first row.
    * Retrieve the result set wrapper from the query-collection user-data
    private ResultSet getResultSet(Object qc) {
    return (ResultSet)getUserDataForCollection(qc);
    * Return either null or a new oracle.jbo.domain.Number
    private static oracle.jbo.domain.Number nullOrNewNumber(BigDecimal b) {
    try {
    return b != null ? new oracle.jbo.domain.Number(b) : null;
    catch (SQLException s) { }
    return null;
    Natalie

  • Need Help With a Stored Procedure

    Help With a Stored Procedure
    Hi everyone.
    I am quite new relative to creating stored procedures, so I anticipate that whatever help I could get here would be very much helpful.
    Anyway, here is my case:
    I have a table where I need to update some fields with values coming from other tables. The other tables, let us just name as tblRef1, tblRef2 and tblRef3. For clarity, let us name tblToUpdate as my table to update. tblToUpdate has the following fields.
    PlanID
    EmployeeIndicator
    UpdatedBy
    CreatedBy
    tblRef1, tblRef2 and tblRef3 has the following fields:
    UserName
    EmpIndicator
    UserID
    In my stored procedure, I need to perform the following:
    1. Check each row in the tblToUpdate table. Get the CreatedBy value and compare the same to the UserName and UserID field of tblRef1. If no value exists in tblRef1, I then proceed to check if the value exists in the same fields in tblRef2 and tblRef3.
    2. If the value is found, then I would update the EmployeeIndicator field in tblToUpdate with the value found on either tblRef1, tblRef2 or tblRef3.
    I am having some trouble writing the stored procedure to accomplish this. So far, I have written is the following:
    CREATE OR REPLACE PROCEDURE Proc_Upd IS v_rec NUMBER;
    v_plan_no tblToUpdate.PLANID%TYPE;
    v_ref_ind tblToUpdate.EMPLOYEEINDICATOR%TYPE;
    v_update_user tblToUpdate.UPDATEDBY%TYPE;
    v_created_by tblToUpdate.CREATEDBY%TYPE;
    v_correct_ref_ind tblToUpdate.EMPLOYEEIDICATOR%TYPE;
    CURSOR cur_plan IS SELECT PlanID, EmployeeIndicator, UPPER(UpdatedBy), UPPER(CreatedBy) FROM tblToUpdate;
    BEGIN
    Open cur_plan;
         LOOP
         FETCH cur_plan INTO v_plan_no, v_ref_ind, v_update_user, v_created_by;
              EXIT WHEN cur_plan%NOTFOUND;
              BEGIN
              -- Check if v_created_by has value.
                   IF v_created_by IS NOT NULL THEN
                   -- Get the EmpIndicator from the tblRef1, tblRef2 or tblRef3 based on CreatedBy
                   SELECT UPPER(EmpIndicator)
                        INTO v_correct_ref_ind
                        FROM tblRef1
                        WHERE UPPER(USERNAME) = v_created_by
                        OR UPPER(USERID) = v_created_by;
                        IF v_correct_ref_ind IS NOT NULL THEN
                        -- Update the Reference Indicator Field in the table TRP_BUSPLAN_HDR_T.
                             UPDATE TRP_BUSPLAN_HDR_T SET ref_ind = v_correct_ref_ind WHERE plan_no = v_plan_no;
                        ELSIF
                        -- Check the Other tables here????
                        END IF;
                   ELSIF v_created_by IS NULL THEN
                   -- Get the EmpIndicator based on the UpdatedBy
                        SELECT UPPER(EmpIndicator)
                        INTO v_correct_ref_ind
                        FROM tblRef1
                        WHERE UPPER(USERNAME) = v_update_user
                        OR UPPER(USERID) = v_created_by;
                        IF v_correct_ref_ind IS NOT NULL THEN
                        -- Update the Reference Indicator Field in the table TRP_BUSPLAN_HDR_T.
                             UPDATE TRP_BUSPLAN_HDR_T SET ref_ind = v_correct_ref_ind WHERE plan_no = v_plan_no;
                        ELSIF
                        -- Check the Other tables here????
                        END IF;
                   END IF;
              END;
         END LOOP;
         CLOSE cur_plan;
         COMMIT;
    END
    Please take note that the values in the column tblToUpdate.UpdatedBy or tblToUpdate.CreatedBy could match either the UserName or the UserID of the table tblRef1, tblRef2, or tblRef3.
    Kindly provide more insight. When I try to execute the procedure above, I get a DATA NOT FOUND ERROR.
    Thanks.

    Ah, ok; I got the updates the wrong way round then.
    BluShadow's single update sounds like what you need then.
    I also suggest you read this AskTom link to help you see why you should choose to write DML statements before choosing to write cursor + loops.
    In general, when you're being asked to update / insert / delete rows into a table or several tables, your first reaction should be: "Can I do this in SQL?" If you can, then putting it into a stored procedure is usually just a case of putting the sql statement inside the procedure header/footers - can't really get much more simple than that! *{;-)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • When inserting 2 column details in a single table using Stored Procedure.Only 2 Column details getting inserted.1column details are not getting into the table.Please see the below script and help me to change.

    Line 390 Under the (Insert into SALES_TRADEIN Table)
    I need to insert (TradeIn_1_VIN) Values If there is no values in (TradeIn_1_VIN) then i have to insert (TradeIn_2_VIN) values to the (SALES_TRADEIN) Table.
    After i run then below script only (TradeIn_2_VIN) values are get inserted in the table. (TradeIn_1_VIN) are not getting loaded in to the table.
    I think there is the problem from Line No (404 to 414) Please help me change those particular lines to insert (TradeIn_1_VIN) Values also.If there is no details then (TradeIn_2_VIN) need to be inserted.
    -- =============================================
    -- Stored Procedure for Flatfile_Sales
    -- =============================================
    USE [IconicMarketing]
    ---==========Sales_Cursor
    --USE [IconicMarketing]
    --GO
    DECLARE
    @FileType
    varchar(50),
    @ACDealerID
    varchar(50),
    @ClientDealerID
    varchar(50),
    @DMSType
    varchar(50),
    @DealNumber
    varchar(50),
    @CustomerNumber
    varchar(50),
    @CustomerName
    varchar(50),
    @CustomerFirstName
    varchar(50),
    @CustomerLastName
    varchar(50),
    @CustomerAddress
    varchar(50),
    @CustomerCity
    varchar(50),
    @CustomerState
    varchar(50),
    @CustomerZip
    varchar(50),
    @CustomerCounty
    varchar(50),
    @CustomerHomePhone
    varchar(50),
    @CustomerWorkPhone
    varchar(50),
    @CustomerCellPhone
    varchar(50),
    @CustomerPagerPhone
    varchar(50),
    @CustomerEmail
    varchar(50),
    @CustomerBirthDate
    varchar(50),
    @MailBlock
    varchar(50),
    @CoBuyerName
    varchar(50),
    @CoBuyerFirstName
    varchar(50),
    @CoBuyerLastName
    varchar(50),
    @CoBuyerAddress
    varchar(50),
    @CoBuyerCity
    varchar(50),
    @CoBuyerState
    varchar(50),
    @CoBuyerZip
    varchar(50),
    @CoBuyerCounty
    varchar(50),
    @CoBuyerHomePhone
    varchar(50),
    @CoBuyerWorkPhone
    varchar(50),
    @CoBuyerBirthDate
    varchar(50),
    @Salesman_1_Number
    varchar(50),
    @Salesman_1_Name
    varchar(50),
    @Salesman_2_Number
    varchar(50),
    @Salesman_2_Name
    varchar(50),
    @ClosingManagerName
    varchar(50),
    @ClosingManagerNumber
    varchar(50),
    @F_AND_I_ManagerNumber
    varchar(50),
    @F_AND_I_ManagerName
    varchar(50),
    @SalesManagerNumber
    varchar(50),
    @SalesManagerName
    varchar(50),
    @EntryDate
    varchar(50),
    @DealBookDate
    varchar(50),
    @VehicleYear
    varchar(50),
    @VehicleMake
    varchar(50),
    @VehicleModel
    varchar(50),
    @VehicleStockNumber
    varchar(50),
    @VehicleVIN
    varchar(50),
    @VehicleExteriorColor
    varchar(50),
    @VehicleInteriorColor
    varchar(50),
    @VehicleMileage
    varchar(50),
    @VehicleType
    varchar(50),
    @InServiceDate
    varchar(50),
    @HoldBackAmount
    varchar(50),
    @DealType
    varchar(50),
    @SaleType
    varchar(50),
    @BankCode
    varchar(50),
    @BankName
    varchar(50),
    @SalesmanCommission
    varchar(50),
    @GrossProfitSale
    varchar(50),
    @FinanceReserve
    varchar(50),
    @CreditLifePremium
    varchar(50),
    @CreditLifeCommision
    varchar(50),
    @TotalInsuranceReserve
    varchar(50),
    @BalloonAmount
    varchar(50),
    @CashPrice
    varchar(50),
    @AmountFinanced
    varchar(50),
    @TotalOfPayments
    varchar(50),
    @MSRP varchar(50),
    @DownPayment
    varchar(50),
    @SecurityDesposit
    varchar(50),
    @Rebate
    varchar(50),
    @Term varchar(50),
    @RetailPayment
    varchar(50),
    @PaymentType
    varchar(50),
    @RetailFirstPayDate
    varchar(50),
    @LeaseFirstPayDate
    varchar(50),
    @DayToFirstPayment
    varchar(50),
    @LeaseAnnualMiles
    varchar(50),
    @MileageRate
    varchar(50),
    @APRRate
    varchar(50),
    @ResidualAmount
    varchar(50),
    @LicenseFee
    varchar(50),
    @RegistrationFee
    varchar(50),
    @TotalTax
    varchar(50),
    @ExtendedWarrantyName
    varchar(50),
    @ExtendedWarrantyTerm
    varchar(50),
    @ExtendedWarrantyLimitMiles
    varchar(50),
    @ExtendedWarrantyDollar
    varchar(50),
    @ExtendedWarrantyProfit
    varchar(50),
    @FrontGross
    varchar(50),
    @BackGross
    varchar(50),
    @TradeIn_1_VIN
    varchar(50),
    @TradeIn_2_VIN
    varchar(50),
    @TradeIn_1_Make
    varchar(50),
    @TradeIn_2_Make
    varchar(50),
    @TradeIn_1_Model
    varchar(50),
    @TradeIn_2_Model
    varchar(50),
    @TradeIn_1_ExteriorColor
    varchar(50),
    @TradeIn_2_ExteriorColor
    varchar(50),
    @TradeIn_1_Year
    varchar(50),
    @TradeIn_2_Year
    varchar(50),
    @TradeIn_1_Mileage
    varchar(50),
    @TradeIn_2_Mileage
    varchar(50),
    @TradeIn_1_Gross
    varchar(50),
    @TradeIn_2_Gross
    varchar(50),
    @TradeIn_1_Payoff
    varchar(50),
    @TradeIn_2_Payoff
    varchar(50),
    @TradeIn_1_ACV
    varchar(50),
    @TradeIn_2_ACV
    varchar(50),
    @Fee_1_Name
    varchar(50),
    @Fee_1_Fee
    varchar(50),
    @Fee_1_Commission
    varchar(50),
    @Fee_2_Name
    varchar(50),
    @Fee_2_Fee
    varchar(50),
    @Fee_2_Commission
    varchar(50),
    @Fee_3_Name
    varchar(50),
    @Fee_3_Fee
    varchar(50),
    @Fee_3_Commission
    varchar(50),
    @Fee_4_Name
    varchar(50),
    @Fee_4_Fee
    varchar(50),
    @Fee_4_Commission
    varchar(50),
    @Fee_5_Name
    varchar(50),
    @Fee_5_Fee
    varchar(50),
    @Fee_5_Commission
    varchar(50),
    @Fee_6_Name
    varchar(50),
    @Fee_6_Fee
    varchar(50),
    @Fee_6_Commission
    varchar(50),
    @Fee_7_Name
    varchar(50),
    @Fee_7_Fee
    varchar(50),
    @Fee_7_Commission
    varchar(50),
    @Fee_8_Name
    varchar(50),
    @Fee_8_Fee
    varchar(50),
    @Fee_8_Commission
    varchar(50),
    @Fee_9_Name
    varchar(50),
    @Fee_9_Fee
    varchar(50),
    @Fee_9_Commission
    varchar(50),
    @Fee_10_Name
    varchar(50),
    @Fee_10_Fee
    varchar(50),
    @Fee_10_Commission
    varchar(50),
    @ContractDate
    varchar(50),
    @InsuranceName
    varchar(50),
    @InsuranceAgentName
    varchar(50),
    @InsuranceAddress
    varchar(50),
    @InsuranceCity
    varchar(50),
    @InsuranceState
    varchar(50),
    @InsuranceZip
    varchar(50),
    @InsurancePhone
    varchar(50),
    @InsurancePolicyNumber
    varchar(50),
    @InsuranceEffectiveDate
    varchar(50),
    @InsuranceExpirationDate
    varchar(50),
    @InsuranceCompensationDeduction
    varchar(50),
    @TradeIn_1_InteriorColor
    varchar(50),
    @TradeIn_2_InteriorColor
    varchar(50),
    @PhoneBlock
    varchar(50),
    @LicensePlateNumber
    varchar(50),
    @Cost varchar(50),
    @InvoiceAmount
    varchar(50),
    @FinanceCharge
    varchar(50),
    @TotalPickupPayment
    varchar(50),
    @TotalAccessories
    varchar(50),
    @TotalDriveOffAmount
    varchar(50),
    @EmailBlock
    varchar(50),
    @ModelDescriptionOfCarSold
    varchar(50),
    @VehicleClassification
    varchar(50),
    @ModelNumberOfCarSold
    varchar(50),
    @GAPPremium
    varchar(50),
    @LastInstallmentDate
    varchar(50),
    @CashDeposit
    varchar(50),
    @AHPremium
    varchar(50),
    @LeaseRate
    varchar(50),
    @DealerSelect
    varchar(50),
    @LeasePayment
    varchar(50),
    @LeaseNetCapCost
    varchar(50),
    @LeaseTotalCapReduction
    varchar(50),
    @DealStatus
    varchar(50),
    @CustomerSuffix
    varchar(50),
    @CustomerSalutation
    varchar(50),
    @CustomerAddress2
    varchar(50),
    @CustomerMiddleName
    varchar(50),
    @GlobalOptOut
    varchar(50),
    @LeaseTerm
    varchar(50),
    @ExtendedWarrantyFlag
    varchar(50),
    @Salesman_3_Number
    varchar(50),
    @Salesman_3_Name
    varchar(50),
    @Salesman_4_Number
    varchar(50),
    @Salesman_4_Name
    varchar(50),
    @Salesman_5_Number
    varchar(50),
    @Salesman_5_Name
    varchar(50),
    @Salesman_6_Number
    varchar(50),
    @Salesman_6_Name
    varchar(50),
    @APRRate2
    varchar(50),
    @APRRate3
    varchar(50),
    @APRRate4
    varchar(50),
    @Term2
    varchar(50),
    @SecurityDeposit2
    varchar(50),
    @DownPayment2
    varchar(50),
    @TotalOfPayments2
    varchar(50),
    @BasePayment
    varchar(50),
    @JournalSaleAmount
    varchar(50),
    @IndividualBusinessFlag
    varchar(50),
    @InventoryDate
    varchar(50),
    @StatusDate
    varchar(50),
    @ListPrice
    varchar(50),
    @NetTradeAmount
    varchar(50),
    @TrimLevel
    varchar(50),
    @SubTrimLevel
    varchar(50),
    @BodyDescription
    varchar(50),
    @BodyDoorCount
    varchar(50),
    @TransmissionDesc
    varchar(50),
    @EngineDesc
    varchar(50),
    @TypeCode
    varchar(50),
    @SLCT2
    varchar(50),
    @DealDateOffset
    varchar(50),
    @AccountingDate
    varchar(50),
    @CoBuyerCustNum
    varchar(50),
    @CoBuyerCell
    varchar(50),
    @CoBuyerEmail
    varchar(50),
    @CoBuyerSalutation
    varchar(50),
    @CoBuyerPhoneBlock
    varchar(50),
    @CoBuyerMailBlock
    varchar(50),
    @CoBuyerEmailBlock
    varchar(50),
    @RealBookDate
    varchar(50),
    @CoBuyerMiddleName
    varchar(50),
    @CoBuyerCountry
    varchar(50),
    @CoBuyerAddress2
    varchar(50),
    @CoBuyerOptOut
    varchar(50),
    @CoBuyerOccupation
    varchar(50),
    @CoBuyerEmployer
    varchar(50),
    @Country
    varchar(50),
    @Occupation
    varchar(50),
    @Employer
    varchar(50),
    @Salesman2Commission
    varchar(50),
    @BankAddress
    varchar(50),
    @BankCity
    varchar(50),
    @BankState
    varchar(50),
    @BankZip
    varchar(50),
    @LeaseEstimatedMiles
    varchar(50),
    @AFTReserve
    varchar(50),
    @CreditLifePrem
    varchar(50),
    @CreditLifeRes
    varchar(50),
    @AHRes
    varchar(50),
    @Language
    varchar(50),
    @BuyRate
    varchar(50),
    @DMVAmount
    varchar(50),
    @Weight
    varchar(50),
    @StateDMVTotFee
    varchar(50),
    @ROSNumber
    varchar(50),
    @Incentives
    varchar(50),
    @CASS_STD_LINE1
    varchar(50),
    @CASS_STD_LINE2
    varchar(50),
    @CASS_STD_CITY
    varchar(50),
    @CASS_STD_STATE
    varchar(50),
    @CASS_STD_ZIP
    varchar(50),
    @CASS_STD_ZIP4
    varchar(50),
    @CASS_STD_DPBC
    varchar(50),
    @CASS_STD_CHKDGT
    varchar(50),
    @CASS_STD_CART
    varchar(50),
    @CASS_STD_LOT
    varchar(50),
    @CASS_STD_LOTORD
    varchar(50),
    @CASS_STD_URB
    varchar(50),
    @CASS_STD_FIPS
    varchar(50),
    @CASS_STD_EWS
    varchar(50),
    @CASS_STD_LACS
    varchar(50),
    @CASS_STD_ZIPMOV
    varchar(50),
    @CASS_STD_Z4LOM
    varchar(50),
    @CASS_STD_NDIAPT
    varchar(50),
    @CASS_STD_NDIRR
    varchar(50),
    @CASS_STD_LACSRT
    varchar(50),
    @CASS_STD_ERROR_CD
    varchar(50),
    @NCOA_AC_ID
    varchar(50),
    @NCOA_COA_ADDSRC
    varchar(50),
    @NCOA_COA_MATCH
    varchar(50),
    @NCOA_COA_MOVTYP
    varchar(50),
    @NCOA_COA_DATE
    varchar(50),
    @NCOA_COA_DELCD
    varchar(50),
    @NCOA_COA_RTYPE
    varchar(50),
    @NCOA_COA_RTNCD
    varchar(50),
    @NCOA_COA_LINE1
    varchar(50),
    @NCOA_COA_LINE2
    varchar(50),
    @NCOA_COA_CITY
    varchar(50),
    @NCOA_COA_STATE
    varchar(50),
    @NCOA_COA_ZIP
    varchar(50),
    @NCOA_COA_ZIP4
    varchar(50),
    @NCOA_COA_DPBC
    varchar(50),
    @NCOA_COA_CHKDGT
    varchar(50),
    @NCOA_COA_CART
    varchar(50),
    @NCOA_COA_LOT
    varchar(50),
    @NCOA_COA_LOTORD
    varchar(50),
    @NCOA_COA_URB
    varchar(50),
    @NCOA_COA_Z4LOM
    varchar(50),
    @NCOA_COA_ACTION
    varchar(50),
    @NCOA_COA_QNAME
    varchar(50),
    @NCOA_DPV_AA
    varchar(50),
    @NCOA_DPV_A1
    varchar(50),
    @NCOA_DPV_BB
    varchar(50),
    @NCOA_DPV_CC
    varchar(50),
    @NCOA_DPV_M1
    varchar(50),
    @NCOA_DPV_M3
    varchar(50),
    @NCOA_DPV_N1
    varchar(50),
    @NCOA_DPV_P1
    varchar(50),
    @NCOA_DPV_P3
    varchar(50),
    @NCOA_DPV_RR
    varchar(50),
    @NCOA_DPV_R1
    varchar(50),
    @NCOA_DPV_STATUS
    varchar(50),
    @NCOA_DPV_F1
    varchar(50),
    @NCOA_DPV_G1
    varchar(50),
    @NCOA_DPV_U1
    varchar(50),
    @myerror
    varchar(500),
    @SalesID
    int,
    @errornumber int,
                @errorseverity varchar(500),
                @errorstate int,
                @errorprocedure varchar(500),
                @errorline varchar(50),
                @errormessage varchar(1000);
    DECLARE Sales_Cursor CURSOR FOR 
    SELECT * from FLATFILE_SALES;
    OPEN Sales_Cursor;
     :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    WHILE @@FETCH_STATUS = 0
    BEGIN
    PRINT @VehicleVIN    ;
    --===============================================================================
    -- ****************** insert into Sales Table ***********
    BEGIN TRY
        INSERT INTO Sales 
    IconicDealerID,
    DealNumber,
    CustomerNumber,
    DMSType,
    ContractDate
    VALUES (@ClientDealerID,@DealNumber,@CustomerNumber,@DMSType,@ContractDate);
    END TRY
    BEGIN CATCH
         SELECT
            @errornumber = ERROR_NUMBER()
            ,@errorseverity = ERROR_SEVERITY() 
            ,@errorstate = ERROR_STATE() 
            ,@errorprocedure = ERROR_PROCEDURE() 
            ,@errorline = ERROR_LINE()
            ,@errormessage = ERROR_MESSAGE();
           :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    @errornumber ,
                @errorseverity ,
                @errorstate,
                @errorprocedure,
                @errorline,
                @errormessage);
    END CATCH
    PRINT @errornumber;
    PRINT @errorseverity;
    PRINT @errorprocedure;
    PRINT @errorline;
    PRINT @errormessage;
    PRINT @errorstate;
    set @myerror = @@ERROR;
        -- This PRINT statement prints 'Error = 0' because
        -- @@ERROR is reset in the IF statement above.
        PRINT N'Error = ' + @myerror;
    set @SalesID = scope_identity();
    PRINT @SalesID;
    --================================================================================
    --Insert into SALES_TRADEIN Table
    BEGIN TRY
    INSERT INTO SALES_TRADEIN
    SalesID,
    TradeIn_VIN,
    TradeIn_Make,
    TradeIn_Model,
    TradeIn_ExteriorColor,
    TradeIn_Year,
    TradeIn_Mileage,
    TradeIn_Gross,
    TradeIn_Payoff,
    TradeIn_ACV,
    TradeIn_InteriorColor
    VALUES
    @SalesID,
    case when  @TradeIn_1_VIN is not null then @TradeIn_2_VIN end,
    case when  @TradeIn_1_Make is not null  then @TradeIn_2_Make end,
    case when  @TradeIn_1_Model is not null  then @TradeIn_2_Model end,
    case when  @TradeIn_1_ExteriorColor is not null  then @TradeIn_2_ExteriorColor end,
    case when @TradeIn_1_Year is not null  then @TradeIn_2_Year end,
    case when  @TradeIn_1_Mileage is not null  then @TradeIn_2_Mileage end,
    case when @TradeIn_1_Gross is not null  then @TradeIn_2_Gross end,
    case when @TradeIn_1_Payoff is not null  then @TradeIn_2_Payoff end,
    case when @TradeIn_1_ACV is not null  then @TradeIn_2_ACV end,
    case when  @TradeIn_1_InteriorColor is not null  then @TradeIn_2_InteriorColor end
    END TRY
    BEGIN CATCH
    SELECT
            @errornumber = ERROR_NUMBER()
            ,@errorseverity = ERROR_SEVERITY() 
            ,@errorstate = ERROR_STATE() 
            ,@errorprocedure = ERROR_PROCEDURE() 
            ,@errorline = ERROR_LINE()
            ,@errormessage = ERROR_MESSAGE();
          :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    END CATCH

    This is what I've understood from your question. You want to replace @TradeIn_2_VIN value if @TradeIn_1_VIN
    is NULL, else the value of @TradeIn_1_VIN.
    If this is the requirement then, your CASE statement is missing ELSE part. You can re-write this as below
    case when  @TradeIn_1_VIN is null then @TradeIn_2_VIN
    ELSE @TradeIn_1_VIN end,
    or simply you can replace the CASE statement with the below
    COALESCE function,
    COALESCE(@TradeIn_1_VIN, @TradeIn_2_VIN),
    Krishnakumar S

  • Looking for some help with using Oracle stored procedures in vb2010

    First off thank you to whoever lends me a hand with my problem. A little background first I am in a software development class and we are currently building our program using VB (I have no experience in this), and Oracle(currently in a Oracle class so I know how to use Oracle itself just not with VB).
    I am using vb2010 express edition if that helps. Currently I have a stored procedure that takes a 4char "ID" that returns a position (ie, salesperson,manager ect). I want to use the position returned to determine what vb form is displayed (this is acting as a login as you dont want a salesperson accessing the accountants page for payroll ect).
    Here is the code I have currently on the login page of my VB form
    Imports Oracle.DataAccess.Client
    Imports Oracle.DataAccess.Types
    Public Class Login
    Dim conn As New OracleConnection
    Private Sub empID_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles empID.Click
    End Sub
    Private Sub LoginBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoginBtn.Click
    conn.ConnectionString = "User ID = Auto" & _
    ";Password = ********" & _
    ";Data Source = XE"
    conn.Open()
    Dim sq1 As String = "Return_Position" 'name of procedure
    Dim cmd As New OracleCommand(sq1, conn)
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.Add(New OracleParameter("I_EmpID", OracleDbType.Char, 4)).Value = Emp_ID.Text
    Dim dataReader As OracleDataReader = cmd.ExecuteReader
    dataReader.Read()
    Dim position As New ListBox
    position.Items.Add(dataReader.GetString(0)) 'were I am getting an error, I also tried using the dataReader.getstring(0) to store its value in a string but its a no go
    If position.FindStringExact("MANAGER") = "MANAGER" Then
    Me.Hide()
    Dim CallMenu As New Menu()
    CallMenu.ShowDialog()
    End If
    LoginBtn.Enabled = False
    End Sub
    I have read the oracle.net developer guide for using oracle in vb2010 and have successfully gotten through the document however they never use a stored procedure, since the teacher wants this program to user a layered architecture I cannot directly store sql queries like the document does, thus the reason I want to use stored procedures.
    This is getting frustrating getting stuck with this having no background in VB, I could easily do this in c++ using file i/o even through it would be a pain in the rear....

    Hello,
    I am calling Oracle 11g stored procedures from VB.Net 2010. Here is a code sample (based on your code) you should be able to successfully implement in your application.
    Please note that you may have to modify your stored procedure to include an OUT parameter (the employee position) if it doesn't have it yet.
    Private Sub LoginBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoginBtn.Click
    Dim sProcedureName As String = "Return_Position" 'name of stored procedure
    Dim ORConn as OracleConnection, sConn as String
    Dim sPosition as String, sDataSource as String, sSchema as String, sPWD as String
    Dim cmd As OracleCommand
    'please provide below sDataSource, sSchema and sPWD in order to connect to your Oracle DB
    sConn = "Data Source=" & sDataSource & ";User Id=" & sSchema & ";Password=" & sPWD & ";"
    ORConn = New OracleConnection(sConn)
    ORConn.Open()
    cmd = New OracleCommand(sProcedureName, ORConn)
    With cmd
    .CommandType = Data.CommandType.StoredProcedure
    'input parameter in your stored procedure is EmpId
    .Parameters.Add("EmpID", OracleDbType.Varchar2).Value = Emp_ID.Text
    .Parameters.Item("EmpID").Direction = ParameterDirection.Input
    'output parameter in your stored procedure is Emp_Position
    .Parameters.Add("Emp_Position", OracleDbType.Varchar2).Direction = ParameterDirection.Output
    .Parameters.Item("Emp_Position").Size = 50 'max number of characters for employee position
    Try
    .ExecuteNonQuery()
    Catch ex As Exception
    MsgBox(ex.Message)
    Exit sub
    End Try
    End With
    sPosition = cmd.Parameters.Item("Emp_Position").Value.ToString
    'close Oracle command
    If Not Cmd Is Nothing Then Cmd.Dispose()
    Cmd = Nothing
    'close Oracle connection
    If Not ORConn Is Nothing Then
    If not ORConn.State = 0 Then
    ORConn.Close()
    End If
    ORConn.Dispose()
    End If
    ORConn = Nothing
    If UCase(sPosition) = "MANAGER" Then
    Me.Hide()
    Dim CallMenu As New Menu()
    CallMenu.ShowDialog()
    End If
    LoginBtn.Enabled = False
    End Sub
    If you need further assistance with the code, please let me know.
    Regards,
    M. R.

  • Help....on stored procedure (or package)

    Hi,
    I have any problem to create stored procedure in Oracle, Can you help me?
    I have to create a stored procedure (or package) in order to reserve the free rooms to the students in the period comprised between the DATE_START and DATE_END.
    Table of the present rooms in building BL1 (RM): SEX 1 = M - SEX 2 = F SEX = 0 (ROOM WITHOUT SEX)
    BL_ID.....FL_ID.......RM_ID.........SEX......RM_STD.....RM_CAT
    BL1.........1..........101..............1........S........ROOM
    BL1.........1..........102..............0........D........ROOM
    BL1.........1..........103..............2........T........ROOM
    BL1.........2..........201..............2........S........ROOM
    BL1.........2..........202..............1........D........ROOM
    BL1.........2..........203..............1........T........ROOM
    BL1.........3..........301..............2........S........APARTMENT
    BL1.........3..........302..............2........D........APARTMENT
    BL1.........3..........303..............1........T........APARTMENT
    BL1.........3..........304..............1........D........APARTMENT
    BL1.........3..........305..............0........D........APARTMENT
    Table of the students (EM):
    EM_ID...........BL_ID.......FL_ID........RM_ID........COD_STUD
    SABRINA..........BL1..........1............102.........524505
    TAKEM............BL1..........1............103.........569673
    SERAFINO.........BL1..........1............103.........589920
    STELLA...........BL1..........1............102.........574659
    CHIARA...........BL1..........1............101.........587845
    VIDAL............BL1..........1............102.........602877
    ROSARIA..........BL1..........2............202.........517070
    LUCA.............BL1..........2............201.........602743
    DANIELA..........BL1..........2............203.........602865
    ANNAMARIA........BL1..........3............305.........588721
    LUIGI............BL1..........3............304.........546517
    Type of rooms (RM_STD):
    RM_STD.......STD_EM........DESCRIPTION
    D.............4..............DOUBLE
    T.............6..............TRIPLE
    S.............2..............SINGLE
    Tables of the reservations carried out from the students (RMPCT):
    EM_ID......BL_ID........FL_ID......RM_ID......DATE_START.......DATE_END.......COD_STUD
    CHIARA......BL1.........1..........101.......11/02/2004.......12/02/2004.......587845
    CHIARA......BL1.........1..........101.......03/02/2005.......16/02/2005.......587845
    SERAFINO....BL1.........1..........102.......12/02/2004.......19/02/2004.......589920
    VIDAL.......BL1.........1..........102.......16/02/2004.......01/03/2004.......602877
    SERAFINO....BL1.........1..........103.......01/02/2004.......15/02/2004.......589920
    TAKEM.......BL1.........1..........103.......04/02/2005.......10/02/2005.......569673
    LUCA........BL1.........2..........201.......03/02/2005.......23/02/2005.......602743
    ROSARIA.....BL1.........2..........202.......03/02/2005.......16/02/2005.......517070
    DANIELA.....BL1.........2..........203.......03/02/2005.......04/02/2005.......602865
    LUIGI.......BL1.........3..........301.......03/02/2005.......23/02/2005.......546517
    VALERIA.....BL1.........3..........302.......12/02/2004.......16/02/2004.......515348
    CHIARA......BL1.........3..........302.......05/02/2004.......15/02/2004.......587845
    CHIARA......BL1.........3..........304.......10/02/2004.......12/02/2004.......587845
    CHIARA......BL1.........3..........305.......20/01/2004.......04/02/2004.......587845
    ANNAMARIA...BL1.........3..........305.......03/02/2005.......16/02/2005.......588721
    INPUT PARAMETERS:
    CREATE OR REPLACE Procedure RESERVE_ROOMS (stud_name varchar2,
    cod_stud varchar2,
    bl_in varchar2,
    fl_in varchar2,
    rm_in in varchar2,
    sex_in varchar2,
    date_start_in varchar2,
    date_end_in varchar2)
    CONDITIONS:
    verify if there are students in table EM:
    select count (1)
    into v_appo
    from em
    where em_id = stud_name
    and cod_stud = cod_stud;
    if v_appo = 0 then
    insert new student:
              insert into em (em_id,cod_sud,sex)
    values (stud_name,cod_stud,sex_in);
    Now I must verify the free rooms in the period comprised between the DATE_START_IN and DATE_END_IN.
    I tried this query: (seem correct...have you any idea?)
    select bl_id,fl_id,rm_id,RM_STD
    from rm
    where (bl_id,fl_id,rm_id,RM_STD) not in (select a.bl_id,a.fl_id,a.rm_id,A.RM_STD
                             from rm a, rmpct b
                             where a.bl_id=b.bl_id
                             and a.fl_id=b.fl_id
                             and a.rm_id=b.rm_id
                             AND((b.date_start <= TO_DATE(date_start_in, 'dd-mm-YYYY')
                             AND b.date_end >= TO_DATE(date_end_in, 'dd-mm-YYYY'))
                             OR ( b.date_end <= TO_DATE(date_end_in, 'dd-mm-YYYY'))
                             AND b.date_end >= TO_DATE(date_start_in, 'dd-mm-YYYY')
                             OR ( b.date_start >= TO_DATE(date_start_in, 'dd-mm-YYYY')
                             and b.date_start <= TO_DATE(date_end_in, 'dd-mm-YYYY')
                             AND b.date_end >= TO_DATE(date_end_in, 'dd-mm-YYYY'))))
    with this query I get all free rooms in period date_start_in - date_end_in, but I must,also,verify if there are double or triple rooms (reserved) with minus of 2 (double) or minus of 3 (triple) students. If there are I can reserved these rooms.
    I tried to verify with these steps:
    CREATE OR REPLACE VIEW COUNT_EM ( BL_ID,
    FL_ID, RM_ID, NUMBER_EM ) AS
    (SELECT rm.bl_id, rm.fl_id, rm.rm_id, COUNT(*) as numero_em
    FROM em, rm
    WHERE em.bl_id(+) = rm.bl_id
    AND em.fl_id(+) = rm.fl_id
    AND em.rm_id(+) = rm.rm_id
    and rm.rm_std in ('S', 'D', 'T')
    group by rm.bl_id, rm.fl_id, rm.rm_id)
    CREATE OR REPLACE VIEW COUNT_RMPCT ( BL_ID,
    FL_ID, RM_ID, STD_EM, NUMBER_RMPCT
    ) AS
    SELECT rm.bl_id, rm.fl_id, rm.rm_id, rmstd.std_em, COUNT(*) as numero_rmpct
    FROM rm, rmpct,rmstd
    WHERE rmpct.bl_id(+) = rm.bl_id
    AND rmpct.fl_id(+) = rm.fl_id
    AND rmpct.rm_id(+) = rm.rm_id
    and rm.rm_std=rmstd.rm_std
    and rm.rm_std in ('S', 'D', 'T')
    AND((rmpct.date_start <= TO_DATE(date_start_in', 'dd-mm-YYYY')
    AND rmpct.date_end >= TO_DATE(date_end_in, 'dd-mm-YYYY'))
    OR ( rmpct.date_end <= TO_DATE(date_end_in, 'dd-mm-YYYY'))
    AND rmpct.date_end >= TO_DATE(date_start_in, 'dd-mm-YYYY')
    OR ( rmpct.date_start >= TO_DATE(date_start_in, 'dd-mm-YYYY')
    and rmpct.date_start <= TO_DATE(date_end_in, 'dd-mm-YYYY')
    AND rmpct.date_end >= TO_DATE(date_end_in, 'dd-mm-YYYY')))
    group by rm.bl_id, rm.fl_id, rm.rm_id, rmstd.std_em
    AND FINALLY:
    select a.bl_id, a.fl_id, a.rm_id, a.NUMBER_RMPCT, B.NUMBER_EM, a.std_em, (a.std_em - (a.NUMBER_RMPCT+B.NUMBER_EM)) RM_FREE
    from COUNT_RMPCT a, COUNT_EM b
    where a.bl_id=b.bl_id
    and a.fl_id=b.fl_id
    and a.rm_id=b.rm_id
    if RM_FREE > 0 THEN there are free rooms (D or T) between those occupied in that period.
    Now If the room (bl_in,fl_in,rm_in) is free I can reserve inserting it in the table RMPCT:
    INSERT INTO rmpct (bl_id, fl_id, rm_id,em_id,cod_stud,date_start, date_end)
    values(bl_in,fl_in,rm_in,stud_name,cod_stud,date_start_in,date_end_in);
    If I haven't rm_in (can be null) I must reserve the first free room (random).
    after these controls: I update table of the students:
    UPDATE em
    Set bl_id = BL_IN,fl_id= FL_IN,rm_id=rm_in
         where em_id=stud_name
         and cod_stud=cod_stud;
    Finally I must make a control on the sex of the room, because there are rooms that have sex=0
    if RM.SEX <> 0 then
         null
    else
    if rm_cat = 'ROOM' then
    UPDATE rm
    set sex = sex_in
    where bl_id = in
    and fl_id = in
    and rm_id = in;
    if rm_cat = 'APARTMENT' then (update on all rooms)
    UPDATE rm
    set sex = sex_in
    where bl_id = in
    and fl_id = in;
    IF v_appo > 0 then
         Same controls except:      insert into em (em_id,cod_sud,sex)
                   values (stud_name,cod_stud,sex_in);
    How I can insert in one stored procedure (or package) all these instructions and controls?
    Thanks in advance!

    In the following demonstation, I have changed the names of some of your variables, in order to standardize them. I have prefaced input parameters with p_ and local variables with v_ and followed them with the name of the column that they are associated with when appropriate. This avoids conflicts with any column names and makes the code easier to read and follow. I have also used table_name.column_name%type to specify the data type associated with the variables instead of using varchar2. That way, if the data type of the columns changes, the code does not have to be updated. This is standard practice.
    In your first insert statement, you have attempted to insert sex into the em table, but there is no sex column in the em table data that you displayed, so I removed the sex.
    Instead of using a complicated mess of views and such to check whether there is a room available and then assign it, I have used just one select statement to select an available room and used an exception clause that handles a no_data_found exception to deal with when there is no room available.
    I have greatly simplified your checking of dates within that select statement.
    You were on the right track with the outer joins and grouping and checking for single, double, or triple rooms. Instead of count, I have used sum and nvl2, so that only the occupied rooms are counted and the rows generated by the outer join are zeroes.
    I have used the nvl function to allow for null values in the input parameters, so that any room can be selected. I used dbms_random.random to ensure that the rows are ordered randomly, but you can leave that out if it is really not that critical that the result be truly random and any row will do. I have used rownum=1 in an outer query to select just one row.
    When you select from a table in pl/sql, you have to select into something. You cannot just issue a select statement, then use an if statement to compare some value in the select statement. For example, you cannot use "if rm.sex ..." you have to select rm.sex into a variable, like v_sex, then use "if v_sex ...". So, I have selected the result of the select statement into local variables, then used those variables for comparisons. I have also used those variables for inserting and updating the appropriate tables, rather than just using the original input parameters, since some of them may have been null.
    In the example below, I have demonstrated how the procedure rejects an unavailable room, accepts a specific available room, and randomly assigns a room.
    -- procedure:
    scott@ORA92> CREATE OR REPLACE PROCEDURE reserve_rooms
      2    -- input parameters:
      3    (p_em_id      IN em.em_id%TYPE,
      4       p_cod_stud   IN em.cod_stud%TYPE,
      5       p_bl_id      IN rm.bl_id%TYPE,
      6       p_fl_id      IN rm.fl_id%TYPE,
      7       p_rm_id      IN rm.rm_id%TYPE,
      8       p_sex          IN rm.sex%TYPE,
      9       p_date_start IN VARCHAR2,
    10       p_date_end   IN VARCHAR2)
    11  AS
    12    -- local variables:
    13    v_appo          INTEGER;
    14    v_bl_id          rm.bl_id%TYPE;
    15    v_fl_id          rm.fl_id%TYPE;
    16    v_rm_id          rm.rm_id%TYPE;
    17    v_rm_cat      rm.rm_cat%TYPE;
    18    v_sex          rm.sex%TYPE;
    19  BEGIN
    20    -- verify if the student is in table em:
    21    SELECT COUNT (*)
    22    INTO   v_appo
    23    FROM   em
    24    WHERE  em_id = p_em_id
    25    AND    cod_stud = p_cod_stud;
    26    -- if the student is not in table em, then insert new student:
    27    IF v_appo = 0 THEN
    28        INSERT INTO em (em_id, cod_stud)
    29        VALUES (p_em_id, p_cod_stud);
    30    END IF;
    31    BEGIN
    32        -- find available room:
    33        SELECT bl_id, fl_id, rm_id, sex, rm_cat
    34        INTO     v_bl_id, v_fl_id, v_rm_id, v_sex, v_rm_cat
    35        FROM     (SELECT rm.bl_id, rm.fl_id, rm.rm_id, rm.sex, rm.rm_cat
    36             FROM     rmpct, rm
    37             WHERE     rm.bl_id = rmpct.bl_id (+)
    38             AND     rm.fl_id = rmpct.fl_id (+)
    39             AND     rm.rm_id = rmpct.rm_id (+)
    40             AND     rm.bl_id = NVL (p_bl_id, rm.bl_id)
    41             AND     rm.fl_id = NVL (p_fl_id, rm.fl_id)
    42             AND     rm.rm_id = NVL (p_rm_id, rm.rm_id)
    43             AND     (rm.sex   = p_sex OR rm.sex = 0)
    44             AND     rmpct.date_start (+) <= TO_DATE (p_date_end, 'DD-MM-YYYY')
    45             AND     rmpct.date_end (+) >= TO_DATE (p_date_start, 'DD-MM-YYYY')
    46             GROUP     BY rm.bl_id, rm.fl_id, rm.rm_id, rm.sex, rm.rm_cat, rm.rm_std
    47             HAVING SUM (NVL2 (rmpct.rm_id (+), 1, 0))
    48                 < DECODE (rm_std, 'S', 1, 'D', 2, 'T', 3)
    49             ORDER     BY DBMS_RANDOM.RANDOM)
    50        WHERE ROWNUM = 1;
    51        -- reserve room:
    52        INSERT INTO rmpct (bl_id, fl_id, rm_id, em_id, cod_stud, date_start, date_end)
    53        VALUES (v_bl_id, v_fl_id, v_rm_id, p_em_id, p_cod_stud,
    54             TO_DATE (p_date_start, 'DD-MM-YYYY'),
    55             TO_DATE (p_date_end, 'DD-MM-YYYY'));
    56        -- update students:
    57        UPDATE em
    58        SET     bl_id = v_bl_id, fl_id = v_fl_id, rm_id = v_rm_id
    59        WHERE     em_id = p_em_id
    60        AND     cod_stud = p_cod_stud;
    61        -- update sex of room or apartment floor:
    62        IF v_sex = 0 THEN
    63          IF v_rm_cat = 'ROOM' THEN
    64            UPDATE rm
    65            SET    sex = p_sex
    66            WHERE  bl_id = v_bl_id
    67            AND    fl_id = v_fl_id
    68            AND    rm_id = v_rm_id;
    69          ELSIF v_rm_cat = 'APARTMENT' THEN
    70            UPDATE rm
    71            SET    sex = p_sex
    72            WHERE  bl_id = v_bl_id
    73            AND    fl_id = v_fl_id;
    74          END IF;
    75        END IF;
    76    EXCEPTION
    77        -- if no room is available:
    78        WHEN NO_DATA_FOUND THEN
    79          RAISE_APPLICATION_ERROR (-20001, 'Sorry, there is no such room available.');
    80    END;
    81  END reserve_rooms;
    82  /
    Procedure created.
    scott@ORA92> SHOW ERRORS
    No errors.
    -- rejects unavailable room of wrong sex:
    scott@ORA92> EXECUTE reserve_rooms ('BARBARA', 654321, 'BL1', 1, 101, 2, '04-02-2005', '10-02-2005')
    BEGIN reserve_rooms ('BARBARA', 654321, 'BL1', 1, 101, 2, '04-02-2005', '10-02-2005'); END;
    ERROR at line 1:
    ORA-20001: Sorry, there is no such room available.
    ORA-06512: at "SCOTT.RESERVE_ROOMS", line 79
    ORA-06512: at line 1
    -- accepts available room of same sex:
    scott@ORA92> EXECUTE reserve_rooms ('BARBARA', 654321, 'BL1', 1, 103, 2, '04-02-2005', '10-02-2005')
    PL/SQL procedure successfully completed.
    -- assigns random available room of same or no sex:
    scott@ORA92> EXECUTE reserve_rooms ('BARBARA', 654321, NULL, NULL, NULL, 2, '11-02-2005', '23-02-2005')
    PL/SQL procedure successfully completed.
    -- results:
    scott@ORA92> -- one and only one row added to em table:
    scott@ORA92> SELECT * FROM em WHERE em_id = 'BARBARA'
      2  /
    EM_ID           BL_I      FL_ID      RM_ID   COD_STUD
    BARBARA         BL1           1        102     654321
    scott@ORA92> -- rooms reserved and other people who have reserved same room
    scott@ORA92> -- (there are 3 who reserved a double room, but only 2 at a time):
    scott@ORA92> SELECT *
      2  FROM   rmpct
      3  WHERE  (bl_id, fl_id, rm_id) IN
      4           (SELECT bl_id, fl_id, rm_id
      5            FROM   rmpct
      6            where  em_id = 'BARBARA')
      7  /
    EM_ID           BL_      FL_ID      RM_ID DATE_STAR DATE_END    COD_STUD
    BARBARA         BL1          1        102 11-FEB-05 23-FEB-05     654321
    SERAFINO        BL1          1        102 12-FEB-04 19-FEB-04     589920
    VIDAL           BL1          1        102 16-FEB-04 01-MAR-04     602877
    SERAFINO        BL1          1        103 01-FEB-04 15-FEB-04     589920
    TAKEM           BL1          1        103 04-FEB-05 10-FEB-05     569673
    BARBARA         BL1          1        103 04-FEB-05 10-FEB-05     654321
    6 rows selected.
    scott@ORA92> -- rooms reserved are all correct sex
    scott@ORA92> -- (note that room 102 was updated from 0 to 2):
    scott@ORA92> SELECT *
      2  FROM   rm
      3  WHERE  (bl_id, fl_id, rm_id) IN
      4           (SELECT bl_id, fl_id, rm_id
      5            FROM   rmpct
      6            where  em_id = 'BARBARA')
      7  /
    BL_      FL_ID      RM_ID        SEX R RM_CAT
    BL1          1        102          2 D ROOM
    BL1          1        103          2 T ROOM
    scott@ORA92>

  • Help Needed in Creating Java Class and Java Stored Procedures

    Hi,
    Can anyone tell how can i create Java Class, Java Source and Java Resource in Oracle Database.
    I have seen the Documents. But i couldn't able to understand it correctly.
    I will be helpful when i get some Examples for creating a Java Class, Java Source and Stored Procedures with Java with details.
    Is that possible to Create a Java class in the oracle Database itself ?.
    Where are the files located for the existing Java Class ?..
    Help Needed Please.
    Thanks,
    Murali.v

    Hi Murali,
    Heres a thread which discussed uploading java source file instead of runnable code on to the database, which might be helpful :
    Configure deployment to a database to upload the java file instead of class
    The files for the java class you created in JDev project is located in the myworks folder in jdev, eg, <jdev_home>\jdev\mywork\Application1\Project1\src\project1
    Hope this helps,
    Sunil..

  • Help needed in stored procedures

    Hi,
    I wrote a stored procedure when i execute it. i get the error
    ORA-00942: table or view does not exist
    ORA-06512: at "SANDEEP.PROC_INS_TEMP_NAC_GL", line 18
    ORA-06512: at line 9
    I was unable to resolve this error please help.
    CREATE OR REPLACE PROCEDURE PROC_INS_TEMP_NAC_GL(
    p_bu IN STRING,
    p_period IN STRING
    IS
    sql_stmt varchar2(1000);
    cnt number;
    BEGIN
         SELECT count(view_name) INTO cnt FROM sys.all_views where view_name = UPPER(p_bu||'_v_ldga') and owner = 'SUN';
         sql_stmt := 'INSERT INTO temp_nac_gl'||
         ' SELECT ''' || p_bu ||'''BU, gl.ACCNT_CODE , gl.ANAL_T0 , gl.ANAL_T1 , gl.PERIOD , gl.MEMO_AMT , gl.AMOUNT , gl.REGION, gl.ANAL_T3'||
                   ' FROM sun.'|| p_bu ||'_v_ldga gl, temp_acnt_grp acnt' ||
                   ' WHERE gl.accnt_code = acnt.acnt_code ' ||
                   ' AND acnt.bu = '''|| p_bu ||'''' ||
                   ' AND gl.period <= '''|| p_period || '''' ||
                   ' ORDER BY gl.REGION';
    EXECUTE IMMEDIATE sql_stmt;
    END;
    /

    If you are accessing a object from a Oracle procedure/function then you need direct rights and not through roles.
    You can check this by executing a SELECT from SQL plus , if you are able to see the table then type the following commond
    SQL> set role none;
    SQL> SELECT statement
    If it gives an error then you dont have direct rights.
    Thanks
    Edited by: Himanshu Kandpal on May 14, 2009 5:04 PM

  • Help on writing pl/sql stored procedure to accept input in xml format

    Hi All,
    I need to write a pl.sql stored procedure which would be getting the input as an xml.
    The requirement is that xml data recieved in below fashion needs to be inserted to 3 different tables.
    The tags under the root node directly needs to be inserted into Table1
    The tags under the first element of the root node needs to be inserted into Table2
    Can anybody help me on how to write a stored procedure which could take up the below xml as input and insert the data received into 3 different tables.
    Any sample code.pointers to achieve this could be of great help.
    The structure of the xml would be as follows:
    <AssemblyProduct>
    <AssemblyHeader>
    <Name></Name>
    <AssemblyId></AssemblyId>
    <ListOfHCSIFFs><HCSIFFHeader><Id></Id> </HCSIFFHeader> </ListOfHCSIFFs>
    <ListOfHCSIFFs><HCSIFFHeader><Id></Id> </HCSIFFHeader> </ListOfHCSIFFs>
    <ListOfHCSIFFs><HCSIFFHeader><Id></Id> </HCSIFFHeader> </ListOfHCSIFFs>
    </AssemblyHeader>
    <AssemblyHeader>
    <Name></Name>
    <AssemblyId></AssemblyId>
    </AssemblyHeader>
    <AssemblyHeader></AssemblyHeader>
    <ApplicationId></ApplicationId>
    <ApplicationName></ApplicationName>
    <ApplicationValidFrom></ApplicationValidFrom>
    <ApplicationValidTo></ApplicationValidTo>
    </AssemblyProduct>

    Well you could write your procedure to accept a parameter of XMLTYPE datatype and then use that value in a query inside the procedure to break the data up as required using something like XMLTABLE e.g.
    -- Nested repeating groups example:
    WITH t as (select XMLTYPE('
    <RECSET>
      <REC>
        <COUNTRY>1</COUNTRY>
        <POINT>1800</POINT>
        <USER_INFO>
          <USER_ID>1</USER_ID>
          <TARGET>28</TARGET>
          <STATE>6</STATE>
          <TASK>12</TASK>
        </USER_INFO>
        <USER_INFO>
          <USER_ID>5</USER_ID>
          <TARGET>19</TARGET>
          <STATE>1</STATE>
          <TASK>90</TASK>
        </USER_INFO>
      </REC>
      <REC>
        <COUNTRY>2</COUNTRY>
        <POINT>2400</POINT>
        <USER_INFO>
          <USER_ID>3</USER_ID>
          <TARGET>14</TARGET>
          <STATE>7</STATE>
          <TASK>5</TASK>
        </USER_INFO>
      </REC>
    </RECSET>') as xml from dual)
    -- END OF TEST DATA
    select x.country, x.point, y.user_id, y.target, y.state, y.task
    from t
        ,XMLTABLE('/RECSET/REC'
                  PASSING t.xml
                  COLUMNS country NUMBER PATH '/REC/COUNTRY'
                         ,point   NUMBER PATH '/REC/POINT'
                         ,user_info XMLTYPE PATH '/REC/*'
                 ) x
        ,XMLTABLE('/USER_INFO'
                  PASSING x.user_info
                  COLUMNS user_id NUMBER PATH '/USER_INFO/USER_ID'
                         ,target  NUMBER PATH '/USER_INFO/TARGET'
                         ,state   NUMBER PATH '/USER_INFO/STATE'
                         ,task    NUMBER PATH '/USER_INFO/TASK'
                 ) y
       COUNTRY      POINT    USER_ID     TARGET      STATE       TASK
             1       1800          1         28          6         12
             1       1800          5         19          1         90
             2       2400          3         14          7          5And then you can extract and insert whatever parts you want into whatever tables as part of the procedure.

Maybe you are looking for

  • Image source attribute in a CSS ?

    I'm trying to change my static HTML page which contains some <img> tags so that the image attributes are stored in a style sheet. However, I can't see any way to put the 'src' attribute in the CSS. e.g. <td width="1"> <img src="dropdown.gif"> </td> I

  • VS 2013 crashes when trying to check-in code

    Hi, We have the following issue. We are using TFS online with VS 2013. We were fine for a few months and then suddenly developers started having issues when trying to check-in their code. VS would fail and restart each time they try to check-in.  The

  • Patch Tool Missing Mouse Pointer...

    WIERD While using the patch tool, it's patching about 2-3 inches to the left of my mouse pointer, ONLY on one image that I'd adjust the Exposure and Sharpening of. Others are patching normally.

  • Can not deselect edit position in table control

    A table control has a property called editpos.  This property returns the cell cordinates for the cell that the use is editing and is writeable.  The property correctly returns -1 and -2 values depending if a header is selected or nothing is selected

  • TAX condition value not getting calculated

    Hi Gurus, At my client we are having this strange issue in pricing when invoice creation. We've set up copy control rules as copy all unchanged. When I tried creating invoice, all the elements are getting copied, but the tax value is not getting crea