Named parameters in Native SQL

A little background first:
Our website uses Hibernate as it's JPA provider, but we've run into several issues with it, one of which they actively refuse to fix out of pure arrogance, even when we gave them a good patch for it. The other one is a performance issue that can be greatly improved by passing arrays as parameters, which I've read rumours is supported in EclipseLink. I first tried implementing a Hibernate UserType as they've specified and it turns out they never read them into the Map that looks-up parameter types during binding, even though it's loaded from their hibernate.cfg.xml. In other words, they're only pretending to support custom user types, but unless you're writing-out the full manual loading of their configuration, there's no way to do it.
After a day of trying to fix all the relation annotations that EclipseLink finds unacceptable in our project (which only uses native SQL and EntityManager.find for selects) I finally got it running and came to discover you don't support named parameters in native SQL. That was really disappointing, because a few months ago we migrated all our queries to named parameters, because positioning ones were too difficult to track and caused more bugs when we had to add more criterias.
My questions are these:
Are named parameters for native SQL not supported by JPA specifications or because they are considered low priority?
Would you accept a patch that supports them?
Can we really use arrays and/or lists as parameters in queries like this "SELECT * FROM some_table WHERE my_column_a IN ? AND my_column_b NOT IN ?"
If yes to above, would it still work if the first one is an array of integers and the second is an array of strings?
Would it work if it's in native SQL and the column types cannot be resolved due to query complexity?

A little background first:
Our website uses Hibernate as it's JPA provider, but we've run into several issues with it, one of which they actively refuse to fix out of pure arrogance, even when we gave them a good patch for it. The other one is a performance issue that can be greatly improved by passing arrays as parameters, which I've read rumours is supported in EclipseLink. I first tried implementing a Hibernate UserType as they've specified and it turns out they never read them into the Map that looks-up parameter types during binding, even though it's loaded from their hibernate.cfg.xml. In other words, they're only pretending to support custom user types, but unless you're writing-out the full manual loading of their configuration, there's no way to do it.
After a day of trying to fix all the relation annotations that EclipseLink finds unacceptable in our project (which only uses native SQL and EntityManager.find for selects) I finally got it running and came to discover you don't support named parameters in native SQL. That was really disappointing, because a few months ago we migrated all our queries to named parameters, because positioning ones were too difficult to track and caused more bugs when we had to add more criterias.
My questions are these:
Are named parameters for native SQL not supported by JPA specifications or because they are considered low priority?
Would you accept a patch that supports them?
Can we really use arrays and/or lists as parameters in queries like this "SELECT * FROM some_table WHERE my_column_a IN ? AND my_column_b NOT IN ?"
If yes to above, would it still work if the first one is an array of integers and the second is an array of strings?
Would it work if it's in native SQL and the column types cannot be resolved due to query complexity?

Similar Messages

  • Using named parameters with an sql UPDATE statement

    I am trying to write a simple? application on my Windows 7 PC using HTML, Javascript and Sqlite.  I have created a database with a 3 row table and pre-populated it with data.  I have written an HTML data entry form for modifying the data and am able to open the database and populate the form.  I am having trouble with my UPDATE function.  The current version of the function will saves the entry in the last row of the HTML table into the first two rows of the Sqlite data table -- but I'm so worn out on this that I can't tell if it is accidental or the clue I need to fix it.
    This is the full contents of the function . . .
         updateData = new air.SQLStatement();
         updateData.sqlConnection = conn;
         updateData.text = "UPDATE tablename SET Gsts = "Gsts, Gwid = :Gwid, GTitle = :GTitle WHERE GId = ":GId;
              var x = document.getElementsById("formname");
              for (var i = 1, row, row = x.rows[i]; i++) {
                   updateData.parameters[":GId"] = 1;
                   for (var j = 0, col; col=row.cells[j]; j++) {
                        switch(j) {
                             case 0: updateData.parameters[":GTitle"] = col.firstChild.value; break;
                             case 1: updateData.parameters[":Gsts"] = col.firstChild.value; break;
                             case 2: updateData.parameters[":Gwid"] = col.firstChild.value; break;
    Note: When I inspect the contents of the col.firstChild.value cases, they show the proper data as entered in the form -- it just isn't being updated into the proper rows of the Sqlite table.
    Am I using the named parameters correctly? I couldn't find much information on the proper use of parameters in an UPDATE statement.

    Thank you for the notes.  Yes, the misplaced quotes were typos.  I'm handtyping a truncated version of the function so I don't put too much info in the post. And yes, i = 1 'cuz the first rows of the table are titles.  So the current frustration is that I seem to be assigning all the right data to the right parameters but nothing is saving to the database.
    I declare updateData as a variable at the top of the script file
    Then I start a function for updating the data which establishes the sql connection as shown above.
    The correctly typed.text statement is:
            updateData.text = "UPDATE tablename SET Gsts=:Gsts, Gwid=:Gwid, GTitle=:GTitle WHERE GId=:GId";
    (The data I'm saving is entered in text boxes inside table cells.) And the current version of the loop is:
            myTable = document.getElementById("GaugeSts");
            myRows= myTable.rows;
              for(i=1, i<myRows.length, i++) {
                   updateData.parameters[":GId"]=i;
                   for(j=0; j<myRows(i).cells.length, j++) {
                        switch(y) {
                             case 0: updateData.parameters[":GTitle"]=myrows[i].cells[y].firstChild.value; break;
                             case 1: updateData.parameters[":Gsts"]=myrows[i].cells[y].firstChild.value; break;
                             case 2: updateData.parameters[":Gwid"]=myrows[i].cells[y].firstChild.value; break;
                             updateData.execute;
    The whole thing runs without error and when I include the statements to check what's in myrows[i].cells[y].firstChild.value, I'm seeing that the correct data is being picked up for assignment to the parameters and the update. I haven't been able to double check that the contents of the parameters are actually taking the data 'cuz I don't know how to extract the data from the parameters. ( The only reference  I've found so far has said that it is not possible. I'm still researching that one.) I've also tried moving the position of the updateData execution statement to several different locations in the loop andstill nothing updates. 
    I am using a combination of air.Introspector.Console.log to check the results of code and I'm using Firefox's SQlite manager to handle the database.  The database is currently sitting on the Desktop to facilitate testing and I have successfully updated/changed data in this table through the SQLite Manager so I don't think I'm having permission errors and, see below, I have another function successfully saving data to another table.
    I currently have another function that uses ? for the parametersin the .text of a INSERT/REPLACE statement and that one works fine.  But, only one line of data is being saved so there is no loop involved.  I tried changing the UPDATE statement in this function to the INSERT/REPLACE just to make something save back to the database but I can't make that one work either.I've a (And, I've tried so many things now, I don't even remember what actually saved something --albeit incorrectly --to the database in one of my previous iterations with the for loops.)
    I'm currently poring through Sqlite and Javascript tomes to see if I can find what's missing but if anything else jumps out at you with the corrected code, I'd appreciate some ideas.
    Jeane

  • NOT Using Named Parameters in a Native Query

    Hi!
    like it is written in the Toplink JPA Extensions reference Toplink supports using named parameters in native queries.
    See example from http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-extensions.html:
    Example 1-11 Specifying a Named Parameter With #
    Query queryEmployees = entityManager.createNativeQuery(
    "SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = #firstname"
    queryEmployeeByFirstName.setParameter("firstName", "Joan");
    Collection employees = queryEmployees.getResultList();
    But I want to use "#" in the SQL statement so I want to disable this parameter binding somehow and let the query just execute the SELECT statement I deliver.
    I have tried to add the property
    <property name="toplink.jdbc.bind-parameters" value="false"/>
    into the persistence.xml and I have also tried to add the query hint
    query.setHint(TopLinkQueryHints.BIND_PARAMETERS, HintValues.FALSE);
    but none of them prevents the # to be uses as a paramter. this causes the exception:
    Exception [TOPLINK-6132] (Oracle TopLink Essentials - 9.1 (Build b22)): oracle.toplink.essentials.exceptions.QueryException
    Exception Description: Query argument ######' not found in list of parameters provided during query execution.
    Query: ReadAllQuery(de.merck.compas.material.SimilarLocalMaterialListItemBV)
    The SQL Statement is
    SELECT * FROM TABLE (
    CAST ( RCGC.PHA_P_COMPASMDM.LookupSimilarMats
    ( 'COC003','10021500150000000997','30','30','040','standard','','001001','001001','123456','##########','X','X','X','X','U' )
    AS RCGC.PHA_COMPAS_SIMILAR_MATS ) )
    I am using the latest Toplink essentials build together with an Oracle 9.2i DB in a Java SE web application.
    Can anyone give me a little hint what to do?
    Thanks and best regards,
    Alex

    I hope this is what you need:
    [TopLink Fine]: 2007.01.19 02:56:48.278--ServerSession(17712783)--Connection(723185)--Thread(Thread[http-8080-Processor2
    3,5,main])--SELECT APPL_CGP_MATLOC, CHANGE_REQ_MATLOC, CD_PHA_MAT_LOC, LCOMP, LOC_MAT_NAME, APPL_GDM_MATLOC, LOC_MAT_NAM
    E_SHORT, APPL_PDW_MATLOC, PHA_MAT_LOC_LCOMMENT, APPL_TP_MATLOC, DIVISION, APPL_WRS_MATLOC, ARTICLE_ID_MDA, LU_PHA_MAT_LO
    C, LOC_MAT_NAME_OLD, LDT_PHA_MAT_LOC, PHA_MAT_LOC_STATUS, CU_PHA_MAT_LOC, MAT_LOC_ID, RCOMP, MAT_ID FROM RCGC.PHA_V_COMP
    AS_MAT_MATLOC WHERE ((MAT_LOC_ID = '123456') AND (RCOMP = '001001'))
    [TopLink Fine]: 2007.01.19 02:56:48.398--ServerSession(17712783)--Connection(32404901)--Thread(Thread[http-8080-Processo
    r23,5,main])--SELECT MAT_ID, DESCRIPTION, PHA_MATERIAL_LCOMMENT, PACKSIZE, LU_PHA_MATERIAL, PACKSIZE_UNIT, LDT_PHA_MATER
    IAL, CONTAINER_NAME, CU_PHA_MATERIAL, PURPOSE, CD_PHA_MATERIAL, CONTENT, CONTAINER_ID, AI_FACTOR, PHA_MATERIAL_STATUS, C
    MG_SPEC_APP, PROD_LEVEL, PACKAGE_SIZE, PRODUCT_ID FROM RCGC.PHA_V_COMPAS_MATERIAL WHERE (MAT_ID = '10021500150000000997'
    [TopLink Fine]: 2007.01.19 02:56:48.468--ServerSession(17712783)--Connection(723185)--Thread(Thread[http-8080-Processor2
    3,5,main])--SELECT PRODUCT_ID, PROD_GRP_ID, APPL_FORM_NAME, PRODUCT_NAME, GALENIC_FORM_NAME, APPL_FORM_ID, PHA_PRODUCT_S
    TATUS, PHA_PRODUCT_LCOMMENT, GALENIC_FORM_ID, LU_PHA_PRODUCT, INN, LDT_PHA_PRODUCT FROM RCGC.PHA_V_COMPAS_PRODUCT WHERE
    (PRODUCT_ID = 'COC003')
    [TopLink Fine]: 2007.01.19 02:56:48.568--ServerSession(17712783)--Connection(32404901)--Thread(Thread[http-8080-Processo
    r23,5,main])--SELECT APPL_CGP_MATLOC, CHANGE_REQ_MATLOC, CD_PHA_MAT_LOC, LCOMP, LOC_MAT_NAME, APPL_GDM_MATLOC, LOC_MAT_N
    AME_SHORT, APPL_PDW_MATLOC, PHA_MAT_LOC_LCOMMENT, APPL_TP_MATLOC, DIVISION, APPL_WRS_MATLOC, ARTICLE_ID_MDA, LU_PHA_MAT_
    LOC, LOC_MAT_NAME_OLD, LDT_PHA_MAT_LOC, PHA_MAT_LOC_STATUS, CU_PHA_MAT_LOC, MAT_LOC_ID, RCOMP, MAT_ID FROM RCGC.PHA_V_CO
    MPAS_MAT_MATLOC WHERE (MAT_ID = '10021500150000000997')
    [TopLink Warning]: 2007.01.19 02:56:48.638--UnitOfWork(4469532)--Thread(Thread[http-8080-Processor23,5,main])--Exception
    [TOPLINK-6132] (Oracle TopLink Essentials - 9.1 (Build b22)): oracle.toplink.essentials.exceptions.QueryException
    Exception Description: Query argument ######' not found in list of parameters provided during query execution.
    Query: ReadAllQuery(de.merck.compas.material.SimilarLocalMaterialListItemBV)
    Local Exception Stack:
    Exception [TOPLINK-6132] (Oracle TopLink Essentials - 9.1 (Build b22)): oracle.toplink.essentials.exceptions.QueryExcept
    ion
    Exception Description: Query argument ######' not found in list of parameters provided during query execution.
    Query: ReadAllQuery(de.merck.compas.material.SimilarLocalMaterialListItemBV)
    at oracle.toplink.essentials.exceptions.QueryException.namedArgumentNotFoundInQueryParameters(QueryException.jav
    a:206)
    at oracle.toplink.essentials.internal.databaseaccess.DatasourceCall.getValueForInParameter(DatasourceCall.java:6
    86)
    at oracle.toplink.essentials.internal.databaseaccess.DatasourceCall.getValueForInOutParameter(DatasourceCall.jav
    a:704)
    at oracle.toplink.essentials.internal.databaseaccess.DatasourceCall.translateQueryString(DatasourceCall.java:630
    at oracle.toplink.essentials.internal.databaseaccess.DatabaseCall.translate(DatabaseCall.java:850)
    at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQuer
    yMechanism.java:212)
    at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQuer
    yMechanism.java:199)
    at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCa
    llQueryMechanism.java:270)
    at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQu
    eryMechanism.java:600)
    at oracle.toplink.essentials.queryframework.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:302)
    at oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:
    709)
    at oracle.toplink.essentials.queryframework.DatabaseQuery.execute(DatabaseQuery.java:609)
    at oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:677)
    at oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:7
    31)
    at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2218)
    at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:937)
    at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:909)
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:346)
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.getResultList(EJBQueryImpl.java:447)
    at de.merck.compas.material.SimilarLocalMaterialListItemBC.selectList(SimilarLocalMaterialListItemBC.java:40)
    at de.merck.compas.material.SimilarLocalMaterialListItemBC.selectSimilar(SimilarLocalMaterialListItemBC.java:53)
    at de.merck.compas.material.MaterialMaintainFS.init(MaterialMaintainFS.java:158)
    at de.merck.compas.material.MaterialListSV.startMaterialMaintain(MaterialListSV.java:186)
    at de.merck.compas.material.MaterialListSV.processPage(MaterialListSV.java:97)
    at de.merck.jsfw.servletFramework.AbstractServlet.processPage(AbstractServlet.java:141)
    at de.merck.jsfw.servletFramework.ControllerServlet.processLastPage(ControllerServlet.java:240)
    at de.merck.jsfw.servletFramework.ControllerServlet.processRequest(ControllerServlet.java:206)
    at de.merck.jsfw.servletFramework.ControllerServlet.doGet(ControllerServlet.java:181)
    at de.merck.jsfw.servletFramework.ControllerServlet.doPost(ControllerServlet.java:191)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at de.merck.comp.ntml.NTLMFilter.negotiate(NTLMFilter.java:384)
    at de.merck.comp.ntml.NTLMFilter.doFilter(NTLMFilter.java:165)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:432)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java
    :664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Thread.java:595)
    The Toplink manifest file with version number:
    Manifest-Version: 1.0
    Ant-Version: Apache Ant 1.6.5
    Created-By: 1.5.0_09-b03 (Sun Microsystems Inc.)
    Specification-Title: Java Persistence API
    Specification-Vendor: Sun Microsystems, Inc., Oracle Corp.
    Specification-Version: 1.0
    Implementation-Title: TopLink Essentials
    Implementation-Vendor: Sun Microsystems, Inc., Oracle Corp.
    Implementation-Version: 9.1 build: b22
    Thanks again for your help!

  • Invalid column Index error - While consuming Calculation view via Native SQL

    Hi Experts,
    I am trying to consume a Calculation view (sql script one) , which has input parameters, via Native SQL in a ABAP program .
    Code snippet for the same would be as follows , Upon execution, it throws an error "Invalid Column Index (8) error " . Can anyone help what could be the issue here ?
    Thanks in Advance,
    Suma
    REPORT ZTEST_HANA2.
    *Report to consume Calculation view (script based) from ABAP
    PARAMETERS: ip_docnr type BELNR_D,
                ip_gjahr type GJAHR,
                ip_bukrs type BUKRS,
                ip_blgr type FAGL_RLDNR.
       DATA: LO_SQL_STMT TYPE REF TO CL_SQL_STATEMENT,
              LO_CONN     TYPE REF TO CL_SQL_CONNECTION,
              LO_RESULT   TYPE REF TO CL_SQL_RESULT_SET,
              LV_SQL      TYPE STRING,
              LR_DATA     TYPE REF TO DATA.
        DATA: LX_SQL_EXC           TYPE REF TO CX_SQL_EXCEPTION,
              LT_SEPMAPPS_CLSDINV  TYPE TABLE OF SEPMAPPS_CLSDINV,
              LV_TEXT              TYPE STRING.
        TRY.
    lv_sql = |SELECT * FROM "_SYS_BIC"."DEMO-ABAP/CA_GET_FI_DATA" | &&
                     |WITH PARAMETERS ('placeholder'= ('$$p_DOCNR$$','{ ip_docnr }'),| &&
                      |'placeholder'=('$$p_GJAHR$$','{ ip_gjahr }')| &&
                      |,'placeholder'= ('$$S_BUKRS$$','{ ip_bukrs }')| &&
                      |,'placeholder'= ('$$p_base_ledger$$','{ ip_blgr }') )| .
             LO_CONN = CL_SQL_CONNECTION=>GET_CONNECTION( ).
             "Create an SQL statement to be executed via the connection
              LO_SQL_STMT = LO_CONN->CREATE_STATEMENT( ).
             "Execute the native SQL query
             LO_RESULT = LO_SQL_STMT->EXECUTE_QUERY( LV_SQL ).
             "Read the result into the internal table lt_sepmapps_clsdinv
             GET REFERENCE OF LT_SEPMAPPS_CLSDINV INTO LR_DATA.
             LO_RESULT->SET_PARAM_TABLE( LR_DATA ).
             LO_RESULT->NEXT_PACKAGE( ).
             LO_RESULT->CLOSE( ).
             LO_CONN->CLOSE( ).
        CATCH CX_SQL_EXCEPTION INTO LX_SQL_EXC.
             LV_TEXT = LX_SQL_EXC->GET_TEXT( ).
             MESSAGE LV_TEXT TYPE 'E'.
        ENDTRY.

    Hi Suma,
    Post the SQL you success run directly on Studio together with error message (even if is the Invalid column index error).
    Check there if the parameters case is working properly... Is it really this confusing options:
    p_GJAHR
    S_BUKRS
    p_base_ledger
    Why not all lower or all upper? Anyhow you must test and find which option works according your modeling
    Regards, Fernando Da Rós

  • Native TopLink named query with named parameters

    Hello,
    Defining my metadata in native TopLink xml and using the native TopLink's Session interface I can access and successfully execute a named query using positional parameters (parameters passed to match the ?1 ?2 etc). I used for this the Session.executeQuery(String, Class, List) method e.g.
    select p from Person p where p.name = ?1
    Now, how can I get the same Session to execute named queries using named parameters? None of the Session.executeQuery methods seem suitable ... Am I missing anything here? e.g.
    select p from Person p where p.age = :age
    I can't find in Session http://www.oracle.com/technology/products/ias/toplink/doc/1013/main/b13698/oracle/toplink/sessions/Session.html a good match for this use-case. I would expect something like:
    Session.executeQuery(String queryName, Class target, List argNames, List argValues)
    or
    Session.executeQuery(String queryName, Class target, Map argsKeyedByName)
    but can't find any good match, can anyone please enlighten me?
    Thanks in advance,
    Best regards,
    Giovanni

    Hello Chris,
    Many thanks for your response. I am sorry if I did not explain my problem properly.
    Suppose I already defined a named query in the metadata XXXProject.xml using the <opm:querying ... this JPQL named query "customFinder" already exists and would look something like:
    select p from Person p where p.firstname=:firstname and p.lastname=:lastname and p.birthdate=:birthdate
    now say you want to execute this query from the Session:
    Vector args = new Vector();
    // how do you know the order? you shouldn't know the order!
    // you know only the parameter names and that's what I mean
    // about named parameters
    // This args setup is wrong ... I need a way to specify to which
    // parameter name each argument corresponds to. In other words
    // if the named query where criteria order of parameters is modified
    // perhaps because of pruning composite keys etc you won't break the
    // existing code ...
    args.add(new Date());
    args.add("Azua");
    args.add("Giovanni");
    Session session = ...
    session.executeQuery("customFinder", Person.class, args);
    JPA supports both type of queries positional parameters and named parameters. Your explanation above is only for the first, my question refers to the later.
    I have not yet found the api for this ... though I am investigating along the lines of:
    Query query = session.getQuery("customFinder");
    and then try to assign the arguments in the same order that the parameters are defined in query or?
    Thanks in advance,
    Best regards,
    Giovanni
    Edited by: bravegag on 29.05.2009 08:06

  • PL/SQL named parameters

    When editing a PL/SQL package I can type a package body name and "." and get a list of function/procedures to choose from. When I choose a function/procedure from the list I would like jdeveloper to dump out the function call complete with named parameters similar to the way it generates an anonymous block for you when you choose to run a function or procedure. How does one do this.
    Thanks in advance.

    Hi,
    the best way is to check this feature being avaiable in SQL Developer because JDeveloper 11 will consume their code base for the integrated PSLQL development environment. Let me know if you can't find it in there and I'll fiel an enhancement request against SQL Developer
    Frank

  • Native SQL Performance Difference Between Hard-Coded Value and Parameter

    Hi,
    I have a native SQL (Oracle) query (fairly long & complex with a few sub-queries) that returns in under a second in both ODSI and using an external SQL tool. This query has a hard-coded value for a particular column, namely, a date column.
    When I modify the ODSI function signature so that I pass in a parameter and then replace the hard-coded value in the native SQL with the appropriate parameter binding notation (i.e. '?'), the query takes much longer (2-30 seconds). The duration of the query depends on how many records are actually returned, so it must be running a separate query for each of the results (i.e. the more results returned, the longer the query takes to return).
    What can I do to keep the duration of my ODSI query low while allowing for the parameter?

    OSDI plan with date parameter:
    <?xml version="1.0"?>
    <source ns="fn-bea" name="jdbc.wcb.fineos" kind="relational" tip="jdbc.wcb.fineos">
    <![CDATA[select codeid, description, FEE_CODE_DOC_TYPE, ismax, isovr
    from
    select distinct
    sd.codeid, sd.description,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-MAX (MAXIMUM AMOUNT)'
    ) ISMAX,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-OVR (Overrideable)'
    ISOVR,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-INT (Internet Enterable)'
    ISINT
    ,trow.answerstr FEE_CODE_DOC_TYPE
    from wcbapp.tocorganisation o, wcbapp.tolpartydetails pd, wcbapp.tolserviceagrmtforprovider safp,
    wcbapp.tolserviceagreement sa, wcbapp.tolserviceagreementversion sav, wcbapp.rsrvchrgrsrvagrvrserviceagreem scg_sav,
    wcbapp.tolservicechargegroup scg, wcbapp.tolservicechargegroupversion scgv, wcbapp.tolserviceprovisionagreement spa,
    wcbapp.tolservicedefinition sd
    ,wcbapp.trow trow, wcbapp.tlookupversion tlookupversion, wcbapp.tlookup tlookup
    where
    trow.i_lkpver_rows = tlookupversion.i
    and trow.c_lkpver_rows = tlookupversion.c
    and tlookupversion.i_lookup_versions = tlookup.i
    and tlookupversion.c_lookup_versions = tlookup.c
    and sd.codeid = trow.minstr_1
    and sd.codeid = trow.maxstr_1
    and tlookup.name = 'FeeCodeToDocumentLookup' and
    spa.i_service_serviceratede = sd.i and
    spa.c_service_serviceratede = sd.c and
    spa.i_srchrgrv_serviceratede = scgv.i and
    spa.c_srchrgrv_serviceratede = scgv.c and
    scgv.i_srvchrgr_servicecharge = scg.i and
    scgv.c_srvchrgr_servicecharge = scg.c and
    scg.i = scg_sav.i_from and
    scg.c = scg_sav.c_from and
    scg_sav.i_to = sav.i and
    scg_sav.c_to = sav.c and
    sav.i_srvcagrm_serviceagreem = sa.i and
    sav.c_srvcagrm_serviceagreem = sa.c and
    sa.i = safp.i_srvcagrm_provider and
    sa.c = safp.c_srvcagrm_provider and
    safp.i_prtdtls_serviceagreem = pd.i and
    safp.c_prtdtls_serviceagreem = pd.c and
    pd.i_ocprty_party = o.i and
    pd.c_ocprty_party = o.c and
    ? between safp.effectivedate and safp.enddate and
    o.customerno = ? || ?
    order by sd.codeid
    where ISINT = 1]]>
    <variable name="__fparam0" kind="EXTERNAL">
    </variable>
    <variable name="__fparam1" kind="EXTERNAL">
    </variable>
    <variable name="__fparam2" kind="EXTERNAL">
    </variable>
    </source>
    OSDI plan with date constant:
    <?xml version="1.0"?>
    <source ns="fn-bea" name="jdbc.wcb.fineos" kind="relational" tip="jdbc.wcb.fineos">
    <![CDATA[select codeid, description, FEE_CODE_DOC_TYPE, ismax, isovr
    from
    select distinct
    sd.codeid, sd.description,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-MAX (MAXIMUM AMOUNT)'
    ) ISMAX,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-OVR (Overrideable)'
    ISOVR,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-INT (Internet Enterable)'
    ISINT
    ,trow.answerstr FEE_CODE_DOC_TYPE
    from wcbapp.tocorganisation o, wcbapp.tolpartydetails pd, wcbapp.tolserviceagrmtforprovider safp,
    wcbapp.tolserviceagreement sa, wcbapp.tolserviceagreementversion sav, wcbapp.rsrvchrgrsrvagrvrserviceagreem scg_sav,
    wcbapp.tolservicechargegroup scg, wcbapp.tolservicechargegroupversion scgv, wcbapp.tolserviceprovisionagreement spa,
    wcbapp.tolservicedefinition sd
    ,wcbapp.trow trow, wcbapp.tlookupversion tlookupversion, wcbapp.tlookup tlookup
    where
    trow.i_lkpver_rows = tlookupversion.i
    and trow.c_lkpver_rows = tlookupversion.c
    and tlookupversion.i_lookup_versions = tlookup.i
    and tlookupversion.c_lookup_versions = tlookup.c
    and sd.codeid = trow.minstr_1
    and sd.codeid = trow.maxstr_1
    and tlookup.name = 'FeeCodeToDocumentLookup' and
    spa.i_service_serviceratede = sd.i and
    spa.c_service_serviceratede = sd.c and
    spa.i_srchrgrv_serviceratede = scgv.i and
    spa.c_srchrgrv_serviceratede = scgv.c and
    scgv.i_srvchrgr_servicecharge = scg.i and
    scgv.c_srvchrgr_servicecharge = scg.c and
    scg.i = scg_sav.i_from and
    scg.c = scg_sav.c_from and
    scg_sav.i_to = sav.i and
    scg_sav.c_to = sav.c and
    sav.i_srvcagrm_serviceagreem = sa.i and
    sav.c_srvcagrm_serviceagreem = sa.c and
    sa.i = safp.i_srvcagrm_provider and
    sa.c = safp.c_srvcagrm_provider and
    safp.i_prtdtls_serviceagreem = pd.i and
    safp.c_prtdtls_serviceagreem = pd.c and
    pd.i_ocprty_party = o.i and
    pd.c_ocprty_party = o.c and
    '01-MAY-11' between safp.effectivedate and safp.enddate and
    o.customerno = ? || ?
    order by sd.codeid
    where ISINT = 1]]>
    <variable name="__fparam0" kind="EXTERNAL">
    </variable>
    <variable name="__fparam1" kind="EXTERNAL">
    </variable>
    </source>
    ODSI Audit with date parameter:
    [Thu May 12 13:02:23 GMT-06:00 2011] Starting...
    Query compilation time: 0 ms
    Query evaluation time: 16142 ms
    Operation duration: 16189 ms
    Audit Event:
    common/application
    user: weblogic
    name: ClaimsDataspace
    server: AdminServer
    eventkind: evaluation
    query/cache/queryplan
    found: false
    type: XQUERY_PLAN_CACHE
    query/cache/queryplan
    type: XQUERY_PLAN_CACHE
    inserted: true
    query/performance
    compiletime: 0
    common/session/query/invocation
    time: Thu May 12 13:02:07 GMT-06:00 2011
    blocksize: 65536
    duration: 16001
    common/session/query/invocation
    time: Thu May 12 13:02:23 GMT-06:00 2011
    blocksize: 65536
    duration: 47
    common/session/query/invocation
    time: Thu May 12 13:02:23 GMT-06:00 2011
    blocksize: 65536
    duration: 46
    common/session/query/invocation
    time: Thu May 12 13:02:23 GMT-06:00 2011
    blocksize: 35779
    duration: 16
    query/wrappers/relational
    source: jdbc.wcb.fineos
    sql:
    select codeid, description, FEE_CODE_DOC_TYPE, ismax, isovr
    from
    select distinct
    sd.codeid, sd.description,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-MAX (MAXIMUM AMOUNT)'
    ) ISMAX,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-OVR (Overrideable)'
    ISOVR,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-INT (Internet Enterable)'
    ISINT
    ,trow.answerstr FEE_CODE_DOC_TYPE
    from wcbapp.tocorganisation o, wcbapp.tolpartydetails pd, wcbapp.tolserviceagrmtforprovider safp,
    wcbapp.tolserviceagreement sa, wcbapp.tolserviceagreementversion sav, wcbapp.rsrvchrgrsrvagrvrserviceagreem scg_sav,
    wcbapp.tolservicechargegroup scg, wcbapp.tolservicechargegroupversion scgv, wcbapp.tolserviceprovisionagreement spa,
    wcbapp.tolservicedefinition sd
    ,wcbapp.trow trow, wcbapp.tlookupversion tlookupversion, wcbapp.tlookup tlookup
    where
    trow.i_lkpver_rows = tlookupversion.i
    and trow.c_lkpver_rows = tlookupversion.c
    and tlookupversion.i_lookup_versions = tlookup.i
    and tlookupversion.c_lookup_versions = tlookup.c
    and sd.codeid = trow.minstr_1
    and sd.codeid = trow.maxstr_1
    and tlookup.name = 'FeeCodeToDocumentLookup' and
    spa.i_service_serviceratede = sd.i and
    spa.c_service_serviceratede = sd.c and
    spa.i_srchrgrv_serviceratede = scgv.i and
    spa.c_srchrgrv_serviceratede = scgv.c and
    scgv.i_srvchrgr_servicecharge = scg.i and
    scgv.c_srvchrgr_servicecharge = scg.c and
    scg.i = scg_sav.i_from and
    scg.c = scg_sav.c_from and
    scg_sav.i_to = sav.i and
    scg_sav.c_to = sav.c and
    sav.i_srvcagrm_serviceagreem = sa.i and
    sav.c_srvcagrm_serviceagreem = sa.c and
    sa.i = safp.i_srvcagrm_provider and
    sa.c = safp.c_srvcagrm_provider and
    safp.i_prtdtls_serviceagreem = pd.i and
    safp.c_prtdtls_serviceagreem = pd.c and
    pd.i_ocprty_party = o.i and
    pd.c_ocprty_party = o.c and
    ? between safp.effectivedate and safp.enddate and
    o.customerno = ? || ?
    order by sd.codeid
    where ISINT = 1
    parameters:
    2011-05-01T00:00:00
    DOC
    007492
    time: 16048
    rows: 1967
    query/performance
    evaltime: 16142
    query/service
    result:
    *** removed due to length ***
    query/service
    function: getFeeCodeByCaregiverEffectiveDate1
    arity: 3
    dataservice: ld:org/wcb/claims/payment/FINEOS/physical/SQL.ds
    query:
    import schema namespace t1 = "http://www.test.com/claims/payment" at "ld:org/wcb/claims/payment/FINEOS/physical/schemas/SQL.xsd";
    declare namespace ns0="ld:org/wcb/claims/payment/FINEOS/physical/SQL";
    declare namespace ns1="http://www.w3.org/2001/XMLSchema";
    declare variable $__fparam0 as ns1:dateTime external;
    declare variable $__fparam1 as ns1:string external;
    declare variable $__fparam2 as ns1:string external;
    fn:subsequence(
    for $FeeCode3 in ns0:getFeeCodeByCaregiverEffectiveDate1($__fparam0,$__fparam1,$__fparam2)
         return
                   $FeeCode3
    ,1,5000)
    parameters:
    2011-05-01T00:00:00
    DOC
    007492
    common/time
    duration: 16189
    timestamp: Thu May 12 13:02:07 GMT-06:00 2011
    [Thu May 12 13:02:23 GMT-06:00 2011] End
    ODSI Audit with date constant:
    [Thu May 12 13:10:00 GMT-06:00 2011] Starting...
    Query compilation time: 0 ms
    Query evaluation time: 359 ms
    Operation duration: 375 ms
    Audit Event:
    common/application
    user: weblogic
    name: ClaimsDataspace
    server: AdminServer
    eventkind: evaluation
    query/cache/queryplan
    found: true
    type: XQUERY_PLAN_CACHE
    query/performance
    compiletime: 0
    common/session/query/invocation
    time: Thu May 12 13:10:00 GMT-06:00 2011
    blocksize: 59256
    duration: 359
    query/wrappers/relational
    source: jdbc.wcb.fineos
    sql:
    select codeid, description, FEE_CODE_DOC_TYPE, ismax, isovr
    from
    select distinct
    sd.codeid, sd.description,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-MAX (MAXIMUM AMOUNT)'
    ) ISMAX,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-OVR (Overrideable)'
    ISOVR,
    select count(*) from wcbapp.tolserviceset ss, wcbapp.RSERVICESRVCSETSERVICESETS sss, wcbapp.tolservicedefinition sd1 where
    sss.i_from = sd.i and
    sss.c_from = sd.c and
    sss.i_to = ss.i and
    sss.c_to = ss.c and
    sd1.codeid = sd.codeid and
    ss.name = 'FEEGROUP-INT (Internet Enterable)'
    ISINT
    ,trow.answerstr FEE_CODE_DOC_TYPE
    from wcbapp.tocorganisation o, wcbapp.tolpartydetails pd, wcbapp.tolserviceagrmtforprovider safp,
    wcbapp.tolserviceagreement sa, wcbapp.tolserviceagreementversion sav, wcbapp.rsrvchrgrsrvagrvrserviceagreem scg_sav,
    wcbapp.tolservicechargegroup scg, wcbapp.tolservicechargegroupversion scgv, wcbapp.tolserviceprovisionagreement spa,
    wcbapp.tolservicedefinition sd
    ,wcbapp.trow trow, wcbapp.tlookupversion tlookupversion, wcbapp.tlookup tlookup
    where
    trow.i_lkpver_rows = tlookupversion.i
    and trow.c_lkpver_rows = tlookupversion.c
    and tlookupversion.i_lookup_versions = tlookup.i
    and tlookupversion.c_lookup_versions = tlookup.c
    and sd.codeid = trow.minstr_1
    and sd.codeid = trow.maxstr_1
    and tlookup.name = 'FeeCodeToDocumentLookup' and
    spa.i_service_serviceratede = sd.i and
    spa.c_service_serviceratede = sd.c and
    spa.i_srchrgrv_serviceratede = scgv.i and
    spa.c_srchrgrv_serviceratede = scgv.c and
    scgv.i_srvchrgr_servicecharge = scg.i and
    scgv.c_srvchrgr_servicecharge = scg.c and
    scg.i = scg_sav.i_from and
    scg.c = scg_sav.c_from and
    scg_sav.i_to = sav.i and
    scg_sav.c_to = sav.c and
    sav.i_srvcagrm_serviceagreem = sa.i and
    sav.c_srvcagrm_serviceagreem = sa.c and
    sa.i = safp.i_srvcagrm_provider and
    sa.c = safp.c_srvcagrm_provider and
    safp.i_prtdtls_serviceagreem = pd.i and
    safp.c_prtdtls_serviceagreem = pd.c and
    pd.i_ocprty_party = o.i and
    pd.c_ocprty_party = o.c and
    '01-MAY-11' between safp.effectivedate and safp.enddate and
    o.customerno = ? || ?
    order by sd.codeid
    where ISINT = 1
    parameters:
    DOC
    007492
    time: 344
    rows: 500
    query/performance
    evaltime: 359
    query/service
    result:
    *** removed due to length ***
    query/service
    function: getFeeCodeByCaregiverEffectiveDate1
    arity: 2
    dataservice: ld:org/wcb/claims/payment/FINEOS/physical/SQL.ds
    query:
    import schema namespace t1 = "http://www.test.com/claims/payment" at "ld:org/wcb/claims/payment/FINEOS/physical/schemas/SQL.xsd";
    declare namespace ns0="ld:org/wcb/claims/payment/FINEOS/physical/SQL";
    declare namespace ns1="http://www.w3.org/2001/XMLSchema";
    declare variable $__fparam0 as ns1:string external;
    declare variable $__fparam1 as ns1:string external;
    fn:subsequence(
    for $FeeCode3 in ns0:getFeeCodeByCaregiverEffectiveDate1($__fparam0,$__fparam1)
         return
                   $FeeCode3
    ,1,500)
    parameters:
    DOC
    007492
    common/time
    duration: 375
    timestamp: Thu May 12 13:10:00 GMT-06:00 2011
    [Thu May 12 13:10:00 GMT-06:00 2011] End
    ------------------------------------------------------------------------

  • Page Parameters in PL/SQL Pages

    The OAS User's Guide says:
    "You can define page parameters for PL/SQL Pages. Values for these parameters are passed to bind variables in the PL/SQL code. For example, if the PL/SQL page 'myplsqlpage' contains the PL/SQL statement 'a:=:param1'; and a page parameter is specified named 'param1' with the value '123' (param1=123), this URL is used to access the PL/SQL page in Oracle AS Portal:
    http://myportal/myplsqlpage?param1=123
    In the PL/SQL code, the bind variable 'a' is assigned the value '123'."
    But I did that but I have the following message:
    ORA-01008: not all the variables have been binded (WWS-22518).
    Please I have an example.
    Thanks in advance.

    Hi Patrick,
    Your suggestion seems interesting and simplistic and I wonder if you could make it working. Because, I worked on a similar suggestion some months ago and it did not work. unless I am confusing your idea with something else, it is not designed to work - although it was claimed in the documentation to work. On talking to Oracle we were able to pin down that it was a documentation bug and a new note was created to state that.
    You may wanna see the following Metalink Note which says that passing parameters from a PLSQL page is not allowed.
    regards,
    AMN
    Subject:      Unable To Pass Parameters To A PL/SQL Page
    Doc ID:      Note:550373.1
    Cause
    Page parameters were not designed to work with PL/SQL pages. However the Oracle® Application Server Portal User's Guide states that this is possible.
    This is a documentation bug and it is related to the following unpublished bugs:
    BUG 5007570: GET PARAMETERS IN PL/SQL PAGE
    BUG 3473023: PASSING PARAMETERS TO PL/SQL PAGE IS ERRORING OUT - ORA-1008
    Solution
    -- To implement the solution, please execute the following steps::
    PL/SQL pages do not support to pass parameters. If you need to pass page parameters to a database provider components such as forms and reports, then you need to create a simple page and follow notes below:
    Note 265180.1
    Title: How to pass parameters to a form, which is placed as a
    portlet inside a page?
    Note 287545.1
    Title: How Pass Parameter Via URL to a Report Using Page Parameters

  • Named Parameters in Functions: Possible?

    I want to use named parameters to call PL/SQL functions using JDBC, as is best practice and necessary for default values to work. Unfortunatley all the examples I found are for procedures only. Using a positional registerOutParameter with named register / get methods on the CallableStatement does not work, obiviously.
    Is there any proper way to use named parameters with functions ? Proper does not include writing wrapper procedures nor turning functions into procedures.

    Hi Avi,
    as far as I know the return value of a PL/SQL function does not have a name, as oposed to the parameters of a PL/SQL function, which must have a name. One could argue that the return value of a function is called the same as the function itself. I have tried that option but it does not work.
    Unfortunatley the method OraclePreparedStatement.registerReturnParameter refers to something else than the return value of a PL/SQL function. Is it possible that the developers of the driver have forgotten something?

  • Named Parameters in Queries - the spec vs the Java EE 5 Tutorial

    Hi,
    I've been studying the topic about the named parameters in JPA and found one inconsistency between the spec and the Java EE 5 Tutorial. Could anyone lend me a helping hand understanding it?
    The Java Persistence API spec (ejb-3_0-fr-spec-persistence.pdf) 3.6.3 "Named Parameters" at page 69 reads:
    The use of named parameters applies to the Java Persistence query language, and is not defined for native queries.
    whereas the Java EE 5 Tutorial in the section Named Parameters in Queries (http://java.sun.com/javaee/5/docs/tutorial/doc/PersistenceIntro3.html#wp81563) of The EntityManager reads:
    Named parameters are case-sensitive, and may be used by both dynamic and static queries.
    I think that the reality is that every JPA provider supports named parameters in dynamic and static queries, but it's not fully supported by the spec (yet not forbidden).
    Jacek
    Jacek Laskowski
    http://www.jaceklaskowski.pl

    Hi Jacek,
    These are not conflicting statements. Named parameters apply to the Java Persistence
    Query language only, not to native queries. There are two ways to specifiy
    Java Persistence Query Language queries : dynamically and statically. You can
    either pre-define the query string using @NamedQuery
    static :
    @NamedQuery(name="findPersonByName",
    query="SELECT OBJECT(p) FROM Person p WHERE p.name LIKE :pName")
    OR, pass the query string in at runtime using EntityManger.createQuery
    dynamic :
    em.createQuery("SELECT OBJECT(p) FROM Person p WHERE p.name LIKE :pName")
    The dynamic approach allows you to construct portions of the query string at runtime.
    My example doesn't do that but the point is that use of the createQuery()
    API is considered the dynamic approach.
    The crux of the Java EE 5 Tutorial statement you referenced is that named parameters apply to
    both the static and dynamic use of Java Persistence Query Language queries.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Named Query or Native Query

    Hello,
    I am using native query to search for results on my search page. A friend of mine just told me that I better use named query or the time to get my search results will be too slow.
    Does Named Query give you faster result than Native Query?
    Thanks in advance.
    Regards,
    Hemen

    When you define named queries (note that this is a Hibernate example) you can put them in for example XML,
    <query name="findItemsByDescription">
    <![CDATA[from Item item where item.description like :desc]]>
    </query>or a SQL query like
    <sql-query name="findItemsByDescription">
    <return alias="item" class="Item"/>
    <![CDATA[select {item.*} from item where description like :desc]]>
    </sql-query>You can call these queries by using the same code, for example,
    session.getNamedQuery("findItemsByDescription").setString("desc", description);This is what is being meant by sharing the same calling API.
    When taking about performance. You have to know something about what goes on under the hood.
    You have probably programmed something using straightforward JDBC, so you know how to queries
    get passed to the driver and send to the database. When using HQL or JPA-QL the queries first have
    to be parsed into an SQL language that the database can understand. In this case, we have an extra
    parsing step in between. Note that Native SQL queries, including stored procedure calls, the persistence
    framework still takes care of mapping the JDBC result sets to graphs of persistent objects.
    If you want to include a native SQL hint to instruct the database management systems query optimizer,
    for example, you need to write the SQL yourself. HQL and JPA-QL do not have keywords for this.
    The disadvantage of putting native SQL in your mapping metadata is lost database portability, because
    your mappings, and hence your application, will work only for a particular database. But usually this is of a
    minor concern as you are probably not creating a framework that has to work on every database.
    When you want to get behind the performance of your query, you really have to consult the database
    and look at the execution plan - A DBA can tell you exactly what is good and what can be optimized.

  • Using Select option in Native SQL

    Hi,
    Can any one tell me, how to use select option value in native SQL.
    ie.,
    I want to use select option in where condition. Need to select all the records from table(non-SAP) where date in given range.
    Please suggest.
    Thanks,
    Amal

    Hi
    No!
    U need to find a way to convert a range of select-option to a range for Native SQL, probably it should be better doesn't use a select-option for the date but two parameters: one for date from and one for date to.
    Max

  • Native SQL from ABAP - ORA 02396 max idle time exceeded

    Hello,
      I am trying to read a table outside of the R/3 environment using native SQL statements. I'm getting the data just fine. But every other time (depending on elapsed time), I get the ORA-02396 exceeded maximum idle time, connect again. Here's the SQL code I'm using and I'm obviously not getting disconnected but I'm not sure why. Any help?
    Open a native SQL connection.
      EXEC SQL.
        connect to 'ONECD'
      ENDEXEC.
    Retrieve information from the BVER tables.
      EXEC SQL PERFORMING read_dental.
        select emp_ssn_num, emp_fname, emp_lname,
               to_char(start_date, 'YYYYMMDD') as start_date,
               rec_type,
               to_char(eff_date, 'YYYYMMDD') as eff_date,
               vendor_plan_id
            into :dental
            from opr$8oc.BVER_CURR_DENTAL_MASTER
      ENDEXEC.
      EXEC SQL PERFORMING read_medical.
        select emp_ssn_num, emp_fname, emp_lname, rec_type,
               to_char(start_date, 'YYYYMMDD') as start_date,
               to_char(eff_date, 'YYYYMMDD') as eff_date,
               network_code, pcp_number, patient_flag,
               vendor_plan_id,
               to_char(network_eff_date, 'YYYYMMDD') as
                       network_eff_date,
               to_char(pha_eff_date, 'YYYYMMDD') as
                       pha_eff_date
             into :medical
             from opr$8oc.BVER_CURR_MEDICAL_MASTER
      ENDEXEC.
    Disconnect from the native SQL connection.
      EXEC SQL.
        DISCONNECT 'ONECD'
      ENDEXEC.
    The system log has messages like 'Work process is in reconnect status' and 'Work process has left reconnect status' after the ORA-02396 message. And I specifically do a disconnect at the end and a connect at the beginning, but it looks like it is trying to do a reconnect?
    Thanks,
    Diane

    Hi Daine,
    Oracle Parameter IDLE_TIME set by the administrator.
    1. Since you are using Secondary database
       connection, the connection must
       have been made with the help of BASIS Team.
    2. This secondary database ORACLE
       has some settings/parameters
       which have been set to say 10 minutes, 60 minutes etc.
       , so what happens,
       if there is NO ACTIVITY / NO SQL / NO INTERACTION
       with the database ,
       the connection is IDLE
       and hence ORACLE then disconnects by itself.
    3. Contact your basis team / oracle administarotr
      team to INCREASE this setting.
      (they do it for some security purpose, firewall etc)
    I hope it helps.  
    Regards,
    Amit M.
    Message was edited by: Amit Mittal

  • Program using Native SQL ... Need suggestion.. Look into code

    Hi Friends ,
    I need your Inputs to solve the new requirement , which need to be solve using Native SQL,
    For this i need to connet to data base 'SIP'.
    The table used for this  are SAPI.TRANSACTION
    fields in SAPI.TRANSACTION
             -  SYSTEMCODE
             - BATCH_ID
         and more
    the above two fields are selection parameters based on which i need to get data :
    please rectify the code and also  help me in this
      TRY.
          EXEC SQL.
            CONNECT TO :'SIP'
          ENDEXEC.
          IF sy-subrc NE 0.
    Error Message
          ENDIF.
          EXEC SQL.
            OPEN dbcur FOR
              SELECT SYSTEM CODE   BATCH_ID
                     FROM SAPI.TRANSACTION
    can i use where condition here , i tried to put the selection parameters here
    and tried to put the internal table , but the programs gets terminated,
    How should i get the fields from table SAPI.TRANSACTION
           IF sy-subrc <> 0.
           RAISE EXCEPTION TYPE cx_sy_native_sql_error.
           ENDIF.
          ENDEXEC.
    DO.
      EXEC SQL.
          FETCH NEXT dbcur INTO :BATCH_ID
    Here i want to get batch id and delete data from other table SAPI.BATCH
      ENDEXEC.
      IF sy-subrc <> 0.
        EXIT.
      ELSE.
      ENDIF.
    ENDDO.
          EXEC SQL.
            CLOSE dbcur
          ENDEXEC.
          EXEC SQL.
            DISCONNECT :'SIP'
          ENDEXEC.
      ENDTRY.

    Hi Anirban, I tried that and it still gives the same error:
    - "itab_mytable" cannot be a table, a reference, a string, or contain any of these objects. any of these objects"
    itab_mytable has been declare as an internal table.
    Basically, from the code in the link you gave me, I have made the following changes:
    REPORT demo_native_sql.
    TYPES: BEGIN OF st,
            connid   TYPE spfli-connid,
            cityfrom TYPE spfli-cityfrom,
            cityto   TYPE spfli-cityto,
          END OF st.
    DATA: itab_mytable TYPE TABLE OF st.
    <...>
    EXEC SQL.
      SELECT connid, cityfrom, cityto
      INTO   :itab_mytable
      FROM   spfli
    ENDEXEC.
    But this doesn't work. If the internal table is replaced with a one-lined work area, then the select statement works.

  • Native sql DBCO, CONNECT statement short dump

    Hi ALL ,
    I am facing the  problem here.  please help me out in this.
    i am trying to connce to the external database MSS, i made all the entries in the DBCO t-code and writing the follwoing native sql statement.
    EXEC SQL.
    CONNECT TO 'AAJ' AS 'V'
    ENDEXEC.
    EXEC SQL.
    SET CONNECTION 'V'
    ENDEXEC.
    The above statement is not giving any error  when i activate it but when i execute it is giving me shortdump error .
    I already maintan   entries in DBCON table or DBCO t-code
    And also tel me once it is connect how can i access the data from MSS (Microsoft sql server)i mean what kind of statement.
    helpfull answer will be rewarded.
    Anees
    9886358645
    Message was edited by:
            anees jawad

    Native SQL
    Open SQL allows you to access database tables declared in the ABAP Dictionary regardless of the database platform that you R/3 System is using. Native SQL allows you to use database-specific SQL statements in an ABAP program. This means that you can use database tables that are not administered by the ABAP Dictionary, and therefore integrate data that is not part of the R/3 System.
    As a rule, an ABAP program containing database-specific SQL statements will not run under different database systems. If your program will be used on more than one database platform, only use Open SQL statements.
    Native SQL Statements in ABAP Programs
    To use a Native SQL statement, you must precede it with the EXEC SQL statement, and follow it with the ENDEXEC statement as follows:
    EXEC SQL [PERFORMING  )
    The parameters are separated by commas. You must also specify whether the parameter is for input (IN), output (OUT) or input and output (INOUT). For further information, refer to SAP Note 44977.
    EXEC SQL
       EXECUTE PROCEDURE proc1 ( IN , OUT :y )
    ENDEXEC.
    Cursor Processing
    Cursor processing in Native SQL is similar to that in Open SQL:
    OPEN
      ENDIF.
    ENDDO.
    EXEC SQL.
      CLOSE c1
    ENDEXEC.
    This example opens a cursor, reads data line by line, and closes the cursor again. As in Open SQL, SY-SUBRC indicates whether a line could be read.
    Data Types and Conversions
    Using Native SQL, you can
    Transfer values from ABAP fields to the database
    Read data from the database and process it in ABAP programs.
    Native SQL works without the administrative data about database tables stored in the ABAP Dictionary. Consequently, it cannot perform all of the consistency checks used in Open SQL. This places a larger degree of responsibility on application developers to work with ABAP fields of the correct type. You should always ensure that the ABAP data type and the type of the database column are identical.
    If the database table is not defined in the ABAP Dictionary, you cannot refer directly to its data type. In this case, you should create a uniform type description in the ABAP Dictionary, which can then be used by all application programs.
    If the table is defined in the ABAP Dictionary, you should remember that the sequence of fields in the ABAP Dictionary definition may not be the same as the actual sequence of fields in the database. Using the asterisk (*) in the SELECT clause to read all columns into a corresponding work area would lead to meaningless results. In the worst case, it would cause an error.
    The Native SQL module of the database interface passes a description of the type, size, and memory location of the ABAP fields used to the database system. The relevant database system operations are usually used to access and convert the data. You can find details of these operations in the manuals for the programming interface of the relevant database system. In some cases, Native SQL also performs other compatibility checks.
    The documentation from the various database manufacturers provides detailed lists of combinations of ABAP data types and database column types, both for storing ABAP field values in database tables (INSERT, UPDATE) and for reading database contents into ABAP fields (SELECT). You can also apply these descriptions for the input and output parameters of database procedures. Any combinations not listed there are undefined, and should not be used.
    The following sections provide details of the data types and conversions for individual databases. Although they are database-specific, there are also some common features.
    Recommended type combinations are underlined. Only for these combinations is behavior guaranteed from release to release. For any other combinations, you should assume that the description only applies to the specified release.
    The results of conversions are listed in a results column:
    "OK": The conversion can be performed without loss of data.
    Operations that fail are indicated by their SQL error code. Errors of this kind always lead to program termination and an ABAP short dump.
    In some cases, data is transferred without an SQL error occurring. However, the data is truncated, rounded, or otherwise unusable:
    Right truncation.
    "Left" or "right" applies to the normal way of writing a value. So, for example, if a number is truncated, its decimal places are affected.
    : Left truncation
    : Number is rounded up or down during conversion
    : A number that was "too small" is rounded to 0 (underflow)
    : The conversion result is undefined.
    There are several possible results. The concrete result is either not known at all, or can only be described using a set of rules that is too complicated for practical use.
    : The conversion returns the SQL value NULL.
    : The conversion is performed without fields and unchecked.
    The original data is converted, but without its format being checked. The result may therefore be a value invalid for the result type, which cannot be processed further. An example of this is a date field containing the value "99999999" or "abcdefgh" after conversion.
    Combinations of ABAP data type and database column type can be divided into finer subcategories. Here, for example, using the transfer direction ABAP ® database (INSERT, UPDATE):
    If the width of the ABAP field is greater than that of the database column, the ABAP field may contain values for which there is not enough space in the database column. This can produce other cases: The concrete data value in ABAP finds space in the database column, or not.
    If the ABAP field is at most as long as the database column, there is always space for the ABAP value in the database column.
    Some types, such as numeric columns, expect values in a particular format. This is particularly important in connection with character types, for example, when you want to write an ABAP character field (type C) into an integer column.
    Native SQL for Oracle
    Native SQL for Informix
    Native SQL for DB2 Common Server
    http://help.sap.com/saphelp_nw04/helpdata/en/fc/eb3b8b358411d1829f0000e829fbfe/content.htm

Maybe you are looking for