Usage of Bind Variable

Hi
Can any one help me ineffectively usage of Bind Variables in 11 g. I have the requirement something like I have 10 input parameters. I have to frame a view object in such a way that If I receive either of the 10 input parameters from the User Interface I have to perform a query by setting the inputer parermeters in the where cluase.
I though tof using Bind Variable concept. but the problem is It is always not necessary that I get 10 paremeters from the inputs, I may get 1 or 2 or ...10. If I set the 10 Bind Variables for 10 Input parameters, My view object is not performing well when I pass one value for bind variable when there are no values for remaining bind variables.
What is the best approach in this case?
Thanks

Why not use dynamic runtime named bind variables?
Create a VO method, something like the following
    public void search(String param1, String param2){
        String sql_1 = " AND SOMETHING = :P_PARAM_1)";
        String sql_2 = " AND SOMETHING_ELSE = :P_PARAM_2";
        setWhereClause(null);
        clearWhereState();
        setWhereClause("1=1");
        if (param1 != null && param1.length()>0){
            addWhereClause(sql_1);
            defineNamedWhereClauseParam("P_PARAM_1",null,null);
            setNamedWhereClauseParam("P_PARAM_1",param1);
        if (param2 != null && param2.length()>0){
            addWhereClause(sql_2);
            defineNamedWhereClauseParam("P_PARAM_2",null,null);
            setNamedWhereClauseParam("P_PARAM_2",param2);
        executeQuery();
    protected void clearWhereState() {
            ViewDefImpl viewDef = getViewDef();
            Variable[] viewInstanceVars = null;
            VariableManager viewInstanceVarMgr = ensureVariableManager();
            if (viewInstanceVarMgr != null) {
                viewInstanceVars = viewInstanceVarMgr.getVariablesOfKind(Variable.VAR_KIND_WHERE_CLAUSE_PARAM);
                if (viewInstanceVars != null) {
                    for (Variable v: viewInstanceVars) {
                        // only remove the variable if its not on the view def.
                        if (!hasViewDefVariableNamed(v.getName())) {
                          removeNamedWhereClauseParam(v.getName());
            getDefaultRowSet().setExecuteParameters(null, null, true);
            setWhereClause(null);
            getDefaultRowSet().setWhereClauseParams(null);
        private boolean hasViewDefVariableNamed(String name) {
            boolean ret = false;
            VariableManager viewDefVarMgr = getViewDef().ensureVariableManager();
            if (viewDefVarMgr != null) {
                try {
                    ret = viewDefVarMgr.findVariable(name) != null;
                catch (NoDefException ex) {
                    // ignore
            return ret;
        }

Similar Messages

  • Bind variables in DB Connect SQL Statement in Oracle

    We are looking for ways to improve performance of DB Connect extract from an Oracle database.
    An example command that is created by the Info-Package using a DB-Connect:
    Current
    SELECT "A", "B", "C", "D", "E", "F", "G", "H"
    FROM "GSF_BW"."V_BW_FORCAST_FACT"
    WHERE ("A" = '200904') AND ("B" BETWEEN '100801' AND '101412')
    The calculated cost (calculated by Oracle Optimizer) is 25.145
    Oracle recommends the usage of bind-variables.
    In that case the Statement would need to look like:
    SELECT "A", "B", "C", "D", "E", "F", "G", "H"
    FROM "GSF_BW"."V_BW_FORCAST_FACT"
    WHERE ("PG0R_SUBD" = :b1) AND ("ZCALMONTH" BETWEEN :b2 AND :b3)
    This would reduce the cost to 11.000 which is 40% of the statement before.
    My question now is: Can anything be done to influence the generation of the SQL statement to make it better performing?

    Hi,
    It is always better to test yourself. Using bind variable is always a good practice and optimizer avoids hard parsing (soft parsing will be done here) if bind variables are used.
    So yes, if this function is being executed several times frequently then second execution onwards it may run faster.
    If you want to see actually what is happening behind it, trace it (using tkprof) and see the result.
    See the below link to know more about SQL TRACE and tkprof.
    http://download.oracle.com/docs/cd/E11882_01/server.112/e16638/sqltrace.htm#PFGRF01020
    Regards,
    Avinash
    Edited by: Avinash Tripathi on Nov 16, 2010 11:46 PM

  • Regarding usage of constants while using bind variables

    Hi All,
    Can some one please help me out of this situation?
    I wrote a query in a package in which i am using bind variables for faster execution of the query in loops.
    In the above said scenario i am trying to insert a set of data into a table say 'A' by selecting from some other table say 'B'. But i also need to insert some data which is constant.
    Something like this:
    constant_val varchar2(1):='N';
    for i in 1 .. tab.count
    loop
    insert into A(Col1, Col2) values (select constant_val, B.value from B where B.value = tab(i));
    end loop;
    I wrote the query using bind variables in the manner:
    for i in 1 .. tab.count
    loop
    execute immediate 'insert into A(Col1, Col2) values (select constant_val, B.value from B where B.value = :1)' using tab(i);
    end loop;
    This compiles, but does not run ... error said is PLSQL statement not properly ended.
    I also tried the option of giving constant_value in the using clause and replacing the same in query using a bind variable. It still doesnt work.
    Is there someway by which i can squeeze in the constant value also. Can someone please advise me on this?
    Thanks in advance,
    Praveen G S

    but i was told that if i succeed
    in reducing the hard parsing of queries .. i will get
    better performance results .. Would i say too, at least for OLTP like systems
    but if i cant or rather dont have to use it while
    looping PLSQL tables and accessing data from other
    tables using this data ... then what do we use it
    for?? PL SQL is capable of bulk operations, so loop is less performant method to process data, however, if you can't do it bulk - for whatever reasons - do it in loop.
    My remark was related mostly to dynamic sql, as shoblock already said, it seems to be no reason in your code to use dynamic sql, if you can use static...
    What i not understand as well, why do you select a value from the table, if this value is already in your collection?
    values (select constant_val, B.value from B where B.value = :1)' using tab(i);Best regards
    Maxim

  • Using a query with bind variable with columns defined as raw

    Hi,
    We are on Oracle 10.2.0.4 on Solaris 8. I have a table that has 2 columns defined as raw(18). I have a query from the front end that queries these two raw columns and it uses bind vairables. The query has a performance issue that I need to reproduce but my difficulty is that how to test the query in sqlplus using bind variables (the syntax for bind vairables fails for columns with raw datatype).
    SQL> DESC TEST
    Name                                      Null?    Type
    ID1                                                RAW(18)
    ID2                                                RAW(18)
    SQL> variable b1  RAW(18);
    Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
                        VARCHAR2 (n [CHAR|BYTE]) | NCHAR | NCHAR (n) |
                        NVARCHAR2 (n) | CLOB | NCLOB | REFCURSOR |
                        BINARY_FLOAT | BINARY_DOUBLE ] ]
    The above is the error I get - i cant declare a variable as raw.
    SQL> variable b2  RAW(18);
    Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
                        VARCHAR2 (n [CHAR|BYTE]) | NCHAR | NCHAR (n) |
                        NVARCHAR2 (n) | CLOB | NCLOB | REFCURSOR |
                        BINARY_FLOAT | BINARY_DOUBLE ] ]
    SQL> variable b3  RAW(18);
    Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
                        VARCHAR2 (n [CHAR|BYTE]) | NCHAR | NCHAR (n) |
                        NVARCHAR2 (n) | CLOB | NCLOB | REFCURSOR |
                        BINARY_FLOAT | BINARY_DOUBLE ] ]
    --now the actual query below
    SQL> SELECT * FROM TEST WHERE ID1=:B1 AND ID2 BETWEEN :B2 AND :B3;
    SP2-0552: Bind variable "B3" not declared.
    (this fails due to the errors earlier)Also this is a third party app schema so that we don't have the option of modifying the data type of the columns.
    Thanks,
    Edited by: orausern on May 10, 2011 11:30 AM

    Try anonymous PL/SQL block:
    declare
    b1 RAW(18);
    b2 RAW(18);
    b3 RAW(18);
    begin
    b1:=..;
    b2:=..;
    b3:=..;
    SELECT col1, col2, ..
    INTO ...
    FROM TEST
    WHERE ID1=:B1
    AND ID2 BETWEEN :B2 AND :B3;
    end;
    /

  • Using bind variables (in & out) with dynamic sql

    I got a table that holds pl/sql code snippets to do validations on a set of data. what the code basically does is receiving a ID and returning a number of errors found.
    To execute the code I use dynamic sql with two bind variables.
    When the codes consists of a simpel query, it works like a charm, for example with this code:
    BEGIN
       SELECT COUNT (1)
       INTO :1
       FROM articles atl
       WHERE ATL.CSE_ID = :2 AND cgp_id IS NULL;
    END;however when I get to some more complex validations that need to do calculations or execute multiple queries, I'm running into trouble.
    I've boiled the problem down into this:
    DECLARE
       counter   NUMBER;
       my_id     NUMBER := 61;
    BEGIN
       EXECUTE IMMEDIATE ('
          declare
             some_var number;
          begin
          select 1 into some_var from dual
          where :2 = 61;
          :1 := :2;
          end;
          USING OUT counter, IN my_id;
       DBMS_OUTPUT.put_line (counter || '-' || my_id);
    END;this code doesn't really make any sense, but it's just to show you what the problem is. When I execute this code, I get the error
    ORA-6537 OUT bind variable bound to an IN position
    The error doesn't seem to make sense, :2 is the only IN bind variable, and it's only used in a where clause.
    As soon as I remove that where clause , the code will work again (giving me 61-61, in case you liked to know).
    Any idea whats going wrong? Am I just using the bind variables in a way you're not supposed to use them?
    I'm using Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit

    Correction. With execute immediate binding is by position, but binds do not need to be repeated. So my statement above is incorrect..
    You need to bind it once only - but bind by position. And the bind must match how the bind variable is used.
    If the bind variable never assigns a value in the code, bind as IN.
    If the bind variable assigns a value in the code, bind as OUT.
    If the bind variable assigns a value and is used a variable in any other statement in the code, bind as IN OUT.
    E.g.
    SQL> create or replace procedure FooProc is
      2          cnt     number;
      3          id      number := 61;
      4  begin
      5          execute immediate
      6  'declare
      7          n       number;
      8  begin
      9          select
    10                  1 into n
    11          from dual
    12          where :var1 = 61;       --// var1 is used as IN
    13 
    14          :var2 := n * :var1;     --// var2 is used as OUT and var1 as IN
    15          :var2 := -1 * :var2;    --// var2 is used as OUT and IN
    16  end;
    17  '
    18          using
    19                  in out id, in out cnt;  --// must reflect usage above
    20 
    21          DBMS_OUTPUT.put_line ( 'cnt='||cnt || ' id=' || id);
    22  end;
    23  /
    Procedure created.
    SQL>
    SQL> exec FooProc
    cnt=-61 id=61
    PL/SQL procedure successfully completed.
    SQL>

  • Bind Variable : required - no message, not required - error

    hi
    Please consider the example application created using JDeveloper 11.1.1.6.0
    at http://www.consideringred.com/files/oracle/2012/RequiredOrNotBVarApp-v0.01.zip
    It has these View Objects defined
    - EmployeesReqNoValueBVarVO which has a required Bind Variable, and where clause "last_name like '%' || :LastNameBVar || '%'"
    - EmployeesNotReqNoValueBVarVO which has a NOT required Bind Variable, and where clause "(:LastNameBVar is null or last_name like '%' || :LastNameBVar || '%')"
    The Bind Variable in both View Objects does NOT have a value (no default value, not programmatically set, not entered by the user, ...).
    This "no value set" aspect could be the result of a "development error", but the resulting observed behaviour is at least "peculiar".
    - scenario (sc1) : run "try tryEmployeesReqNoValueBVarVO", see a table filled with rows and NO message about the required Bind Variable
    - scenario (sc2) : run "try tryEmployeesNotReqNoValueBVarVO", see "No data to display." in the table and the "Missing IN or OUT parameter at index:: 1" error for the NOT required Bind Variable for a where clause that can deal with null values
    - question (q1) How can be explained that scenario (sc1) does not result in an error message about the required Bind Variable (and scenario (sc2) does result in an error message about the NOT required Bind Variable)?
    - question (q2) What does the "Required" checkbox for a Bind Variable really mean for Bind Variables used in a where clause of a View Object?
    If the described behaviour can be reproduced (using RequiredOrNotBVarApp-v0.01.zip), confirmations are welcome.
    (Aspects of these scenario's could be related to forum thread "Bind variable required/not required: strange behaviour".)
    many thanks
    Jan Vervecken

    Thanks for your reply Frank.
    Frank Nimphius wrote:
    ... your query actually is dependent on the existence of the bind variable because the bind variable is used in the where clause part. ...Sure, and the Bind Variable does exist (in both (sc1) and (sc2)).
    ... This has nothing to do with whether the bind variable value is checked for NULL and if the value it contains is NULL performs an "all you can eat" type of query. Because the existing, NOT required Bind Variable has not been given a value in scenario (sc2), the check for NULL only makes more explicit that NULL is a valid value for the SQL statement.
    ... Non required bind variables are used in the context of view criteria to avoid missing IN or OUT parameters. ...The "Required" checkbox for a Bind Variable is also available/enabled when the Bind Variable is not used in a View Criteria (in both (sc1) and (sc2)).
    ... In the case of a view criteria, the VO query may be executed without the view criteria applied and for this reason should not fail only because the defined bind variable is not provided. ...No View Criteria in the scenario's (sc1) and (sc2) I descirbe.
    ... If you run the query in the tester, you get
    (java.sql.SQLException) Missing IN or OUT parameter at index:: 1
    and no query is executed at all for EmployeesNotReqNoValueBVarVOSure, that matches scenario (sc2), but the Bind Variable can be configured as NOT required, how can it be missing?
    The JDeveloper help page "Create or Edit Bind Variables Dialog - Variable Page" says:
    "... Alternatively, you can use the SQL Statement page of the Edit View Objects dialog to enter a parameterized WHERE clause. Note that the bind variables you enter in a parameterized SQL WHERE clause will require a valid value at runtime or a runtime exception error will be thrown. ..."
    So, null as a valid value, seems to explain the behaviour in scenario (sc1).
    "... In contrast, when you create a view criteria filter condition that references a named bind variable, you can specify whether the value is required or optional. ..."
    But, the "Required" checkbox is also available (to uncheck) for Bind Variables that are not used in a View Criteria.
    Specifically for the "Required" checkbox the help page says : "... Select if you want to make the value of a name bind variable required for any usage the references the named bind variable. For example, when the value is required (default), all view criteria items that reference the named bind variable will fail to execute unless a valid value is supplied at runtime. Alternatively, you can leave the value not required and use the Create View Criteria dialog to specify whether or not individual view criteria items require the value. ..."
    Again, the focus is on View Criteria, although it can also be unchecked (configuring as NOT Required) for Bind Variables that are not used in a View Criteria (which does not seem to be something you should do).
    But, still, there is a perspective here that makes this possibly very confusing:
    - a View Object where clause with a required Bind Variable, no value set --> results in rows, and NO message about a missing value
    - a View Object where clause with a NOT required Bind Variable, no value set --> results in no rows, and a message about a missing value
    regards
    Jan

  • Simple Q about using a List in a bind variable

    Using jDev 11.1.1.3, still new to this ADF stuff
    In my UI i have a shuttle component that allows the user to move x number of items to the right pane. Each one of these items becomes part of a filter in a where clause of a query on my VO. Can I do this with a bind variable instead of constructing the where clause progromatically?
    I need to accomplish this: vo.setWhereClause(attribute = 'w' OR 'x' OR 'y' OR 'Z'), where the list of params is dynamically generated in the UI.
    Is there a way i can feed a List to a bind variable? Maybe I can use View Criteria to do this?
    Thanks a lot.

    You should use "IN" clause for this scenario:
    Take a look at this blog post that describes the usage -
    http://jobinesh.blogspot.com/2010/09/using-bind-variable-for-sql-statements.html
    Thanks,
    Navaneeth

  • How to use bind variables using in  clause in SQL

    Hi
    Can any one help me in regards Bind variables usage using in clause in sql for String data?
    thans

    Are you looking for a dynamic IN list? As in something like this:
    SELECT ... FROM .. WHERE some_col IN (<dynamic list of stuff that is always changing>)If so check this out:
    [ How can I do a variable IN list?|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:210612357425]

  • Label of attribute when used as View Criteria item with Bind Variable

    I've a VO attribute used in a named search with this requirement:
    The attribute provides has an optional View Criteria item that has a bind variable operand. The bind variable is in the WHERE clause. The attribute has an LOV. The choice list for the specified View Criteria item should display the label "Effective Release". However, in all other contexts, including the search results table and the dropdowns the user can optionally add in an advanced search, the label displayed for the attribute must say "Release".
    In other words, the default label for the attribute should be "Release" in all but one context - which is that when the dropdown list for the viewCriteria item using the bind variable is displayed, the label should say "Effective Release".
    Note that if the user moves to Advanced Search and selects adds the attribute as a search criteria, this latter usage should be labeled as "Release". (in this case, in other words, the dropdown that displays by default and has the bind variable operand is labelled "Effective Release", the one the user added in advance search is labelled "Release")
    here is the View Criteria item source xml:
          <ViewCriteriaItem
            Name="ReleaseId1"
            ViewAttribute="ReleaseId1"
            Operator="="
            Conjunction="AND"
            Value=":v_ReleaseId"
            GenerateIsNullClauseForBindVars="false"
            ValidateBindVars="true"
            IsBindVarValue="true"
            Required="Required"/>I've experimented by putting "Effective Release" as the label for the bind variable as below. However, ADF does not use that value to display, it defers to the attribute value:
    <Variable
        Name="v_ReleaseId"
        Kind="viewcriteria"
        Type="oracle.jbo.domain.Number">
        <Properties>
          <SchemaBasedProperties>
            <LABEL
              ResId="EFFECTIVE_RELEASE_LOV"/>
          </SchemaBasedProperties>
        </Properties>
      </Variable>The reason for the requirement, if it matters, is that the View Criteria item with the bind variable ("Effective Release" queries a range of values using the analytic function rank(); the bind variable is in the WHERE clause. Otherwise, the dropdown that can be added in advanced search ("Release") looks for exact matches on the attribute value. So since the search functionality is different, the label should be different.
    Am using 11g.
    Thanks for your help.

    Hi
    I have found that when using validation type Key Exists and the VO is in the local application, then the bind variable is available in the Create Validation wizard. When I try and create a validator on a VO that is core to all my applications, then I put that VO into an ADF library, the bind variable parameter is not available for mapping to my entity object attribute, even though I can select the VO to create a view accessor from the ADF library.
    Possible bug?

  • SP2-0552: Bind variable not declared error. Any help please?

    Hi Experts,
    I have a question regarding the error that I am getting: SP2-0552: Bind variable "V_COUNT_TOT_BAL" not declared.
    I have 'out' parameters declared in my procedure and executing the same from sql script as shown below:
    set ver off
    set serverout on
    set linesize 8000
    Declare
    Variable v_count_dtl_bal NUMBER(10);
    Variable v_updat_dtl_bal NUMBER(10);
    Variable v_count_tot_bal NUMBER(10);
    Begin
    execute load_abc.insert_abc_bal(:v_count_dtl_bal,:v_updat_dtl_bal,:v_count_tot_bal);
    End;
    exit;
    So, when this sql script runs it given me the above error. However, all the result looks good and there's no problem with the data or anything else that might be impacted. I suspect this error stems from the code in the sql script above.
    Any idea what am I doing wrong?
    Thanks in advance for any inputs.

    Thanks Frank. I still receive the same error if I follow your example or any of the ones explained above. This is what I am getting and still an error underneath:
    Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
              VARCHAR2 (n CHAR) | NCHAR | NCHAR (n) |
              NVARCHAR2 (n) | CLOB | NCLOB | REFCURSOR |
              BINARY_FLOAT | BINARY_DOUBLE ] ]
    Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
              VARCHAR2 (n CHAR) | NCHAR | NCHAR (n) |
              NVARCHAR2 (n) | CLOB | NCLOB | REFCURSOR |
              BINARY_FLOAT | BINARY_DOUBLE ] ]
    Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
              VARCHAR2 (n CHAR) | NCHAR | NCHAR (n) |
              NVARCHAR2 (n) | CLOB | NCLOB | REFCURSOR |
              BINARY_FLOAT | BINARY_DOUBLE ] ]
    SP2-0552: Bind variable "V_COUNT_TOT_BAL" not declared.

  • Sqplus bind variables

    HI
    Can anyone help with why I am getting BIND variable undeclared please ?
    Here is my spec file:
    create or replace
    package  common as
    type recordList is RECORD
      recList VARCHAR2(100)
    type recordList_CV is ref cursor return recordList;
    PROCEDURE generateRecord(p_owner IN VARCHAR2, p_tableName IN VARCHAR2, recMainlist IN OUT recordList_CV);
    end;
    SQLPlus File:
    --variable o VARCHAR2(40);
    --variable t VARCHAR2(40);
    var rc refcusror;
    --:o := 'store';
    --:t := 'employees';
    rem exec common.generateRecord(:o,:t,:rec);
    execute common.generateRecord('store','employees',:rc);
    print rec;
    Output:
    SQL> @common_test.sql
    Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
                VARCHAR2 (n [CHAR|BYTE]) | NCHAR | NCHAR (n) |
                NVARCHAR2 (n) | CLOB | NCLOB | BLOB | BFILE
                REFCURSOR | BINARY_FLOAT | BINARY_DOUBLE ] ]
    SP2-0552: Bind variable "RC" not declared.
    SP2-0552: Bind variable "REC" not declared.

    > var rc refcusror;
    Check spelling.
    Also, REC not declared.

  • Report Performance with Bind Variable

    Getting some very odd behaviour with a report in APEX v 3.2.1.00.10
    I have a complex query that takes 5 seconds to return via TOAD, but takes from 5 to 10 minutes in an APEX report.
    I've narrowed it down to one particular bind. If I hard code the date in it returns in 6 seconds, but if I let the date be passed in from a parameter it takes 5+ minutes again.
    Relevant part of the query (an inline view) is:
    ,(select rglr_lect lect
    ,sum(tpm) mtr_tpm
    ,sum(enrols) mtr_enrols
    from ops_dash_meetings_report
    where meet_ev_date between to_date(:P35_END_DATE,'DD/MM/YYYY') - 363 and to_date(:P35_END_DATE,'DD/MM/YYYY')
    group by rglr_lect) RPV
    I've tried replacing the "to_date(:P35_END_DATE,'DD/MM/YYYY') - 363" with another item which is populated with the date required (and verified by checking session state). If I replace the :P35_END_DATE with an actual date the performance is fine again.
    The weird thing is that a trace file shows me exactly the same Explain Plan as the TOAD Explain where it runs in 5 seconds.
    Another odd thing is that another page in my application has the same inline view and doesn't hit the performance problem.
    The trace file did show some control characters (circumflex M) after each line of this report's query where these weren't anywhere else on the trace queries. I wondered if there was some sort of corruption in the source?
    No problems due to pagination as the result set is only 31 records and all being displayed.
    Really stumped here. Any advice or pointers would be most welcome.
    Jon.

    Don't worry about the Time column, the cost and cardinality are more important to see whther the CBO is making different decisions for whatever reason.
    Remember that the explain plan shows the expected execution plan and a trace shows the actual execution plan. So what you want to do is compare the query with bind variables from an APEX page trace to a trace from TOAD (or sqlplus or whatever). You can do this outside APEX like this...
    ALTER SESSION SET EVENTS '10046 trace name context forever, level 1';Enter and run your SQL statement...;
    ALTER SESSION SET sql_trace=FALSE;This will create a a trace file in the directory returned by...
    SELECT value FROM v$parameter WHERE name = 'user_dump_dest' Which you can use tkprof to format.
    I am assuming that your not going over DB links or anything else slightly unusual?
    Cheers
    Ben

  • How to Dene a Data Link Between Queries: Bind Variables

    This is an interesting topic and I cannot get it to work using Bind Variables.
    I have 2 queries: Q1 and Q2. Q2 needs c_id, account_code and account_type from Q1.
    Whe I run the data template below, I get only the data for Q1.
    Now people may argue that there is no data in Q2 for the relevant clause. So if I even remove the where clause in Q2 I still get no joy i.e Data appears for Q1 but not for Q2
    <dataTemplate name="FLCMR519_DATA_SET" description="Termination Quote Report">
         <parameters>
              <parameter name="cid" dataType="number" defaultValue="1"/>
              <parameter name="p_cln_id" dataType="number" defaultValue="62412"/>
         </parameters>
         <dataQuery>
              <sqlStatement name="Q1">
                   <![CDATA[SELECT qm.qmd_id,
    qm.contract_period,
    qm.quo_quo_id||'/'||qm.quote_no||'/'||qm.revision_no reference_no,
    qm.contract_distance,
    qm.mdl_mdl_id,
    q.qpr_qpr_id,
    q.quo_id,
    q.drv_drv_id,
    qm.revision_user username,
    pb.first_name||' '||pb.last_name op_name,
    pb.telephone_no,
    pb.facsimile_no,
    pb.email,
    q.c_id c_id,
    q.account_type account_type,
    q.account_code account_code,
    m.model_desc,
    ph.payment_description payment_head_desc,
    cl.fms_fms_id,
    cl.start_date,
    cl.end_date,
    cl.actual_end_date,
    cl.con_con_id,
    cl.cln_id,
    cl.term_qmd_id term_qmd_id,
    qm2.contract_period term_period,
    qm2.contract_distance term_distance
    FROM quotations q,
               quotation_models qm,
               contract_lines cl,
               personnel_base pb,
               models m,
               model_types mt,
               payment_headers ph,
               quotation_models qm2
    WHERE q.quo_id = qm.quo_quo_id
           AND cl.cln_id = :p_cln_id
           AND qm.qmd_id = cl.qmd_qmd_id
           AND qm2.revision_user = pb.employee_no (+)
           AND qm.mdl_mdl_id = m.mdl_id
           AND m.mtp_mtp_id = mt.mtp_id
           AND qm.payment_id = ph.payment_header_id
           AND qm2.qmd_id (+) = cl.term_qmd_id
    ]]>
              </sqlStatement>
              <sqlStatement name="Q2">
                   <![CDATA[SELECT ea.c_id,                  ea.account_type,ea.account_code,ea.account_name
    FROM external_accounts ea
                 WHERE ea.c_id = :c_id
                   AND ea.account_type = :account_type
                   AND ea.account_code = :account_code
    ]]>
              </sqlStatement>
         </dataQuery>
    </dataTemplate>

    Defining dataStructure section is mandatory for multiple queries.

  • Can I use bind variable instaed of writing static COLUMN Name

    Hi , I am having a table containing id and column names, the data is stored against that id in other tables. Now I wish to update data into another table so that it goes into apppropriate column without using decode function.
    I am trying to do this:
    EXECUTE IMMEDIATE 'update TEST set :1 = :2
    where PROJECT_ID= :3 and UNIQUE_ID= :4' using P_DEST_COLUMN, P_TEXT_VALUE, P_PROJ_ID, P_TASK_UID;
    the values P_DEST_COLUMN, P_TEXT_VALUE, P_PROJ_ID, P_TASK_UID are populated using a cursor in PL/SQl
    Is this statement valid? If not can you tell me how to do it as I am getting some error I am unable to comprehend.
    thanks
    Rishabh

    Column names cannot be substituted at run-time as bind variables. If you need to specify the column name at run-time, you'd need to construct a new string and execute that string dynamically, i.e.
    EXECUTE IMMEDIATE 'UPDATE test SET ' || p_dest_column || ' = :1 ' || ...From a data model standpoint, storing column names as data elements in another table is generally a rather poor idea. It's likely to make ad-hoc reporting nearly impossible and to cause a lot more parsing than would otherwise be required.
    Justin

  • Dynamic sql and bind variables

    Hi,
    I have a stored procedure which filters a table on 5 five columns. The filters come from the input parameters,
    and these 5 parameters can come in any combination, I mean some of them may be null and some of them may not be null.
    So I constructed the where filter of the query with IF blocks like the following:
    dynamic_query := 'select * from TESTTABLE where 1= 1';
    IF (P1 is not null) THEN
    dynamic_query := dynamic_query || ' AND column1 = :1';
    END IF;
    IF (P2 is not null) THEN
    dynamic_query := dynamic_query || ' AND column2 = :2';
    END IF;
    IF (P3 is not null) THEN
    dynamic_query := dynamic_query || ' AND column3 = :3';
    END IF;
    IF (P4 is not null) THEN
    dynamic_query := dynamic_query || ' AND column4 = :4';
    END IF;
    IF (P5 is not null) THEN
    dynamic_query := dynamic_query || ' AND column5 = :5';
    END IF;
    OPEN CUR_OUT FOR dynamic_query USING P1, P2, P3, P4, P5;
    The problem is how can I construct the USING and bind parameters, I cannot use "USING P1, P2, P3, P4, P5" because some of bind variables
    may not be in dynamic query if the input parameters are null. Is there a way to overcome this problem without writing all the 2 ^ 5 combinations?
    Any help is greatly appreciated.

    here it is in the Tomer Cohen way:
    IF (P1 is not null) THEN
    dynamic_query := dynamic_query || ' AND column1 = :1';
    ELSE
    dynamic_query := dynamic_query || ' AND  :1 IS NULL';
    END IF;
    IF (P2 is not null) THEN
    dynamic_query := dynamic_query || ' AND column2 = :2';
    ELSE
    dynamic_query := dynamic_query || ' AND  :2 IS NULL';
    END IF;
    IF (P3 is not null) THEN
    dynamic_query := dynamic_query || ' AND column3 = :3';
    ELSE
    dynamic_query := dynamic_query || ' AND  :3 IS NULL';
    END IF;
    IF (P4 is not null) THEN
    dynamic_query := dynamic_query || ' AND column4 = :4';
    ELSE
    dynamic_query := dynamic_query || ' AND  :4 IS NULL';
    END IF;
    IF (P5 is not null) THEN
    dynamic_query := dynamic_query || ' AND column5 = :5';
    ELSE
    dynamic_query := dynamic_query || ' AND -1 = :5';
    END IF;
    OPEN CUR_OUT FOR dynamic_query USING P1, P2, P3, P4, P5;Amiel Davis

Maybe you are looking for