Use of variables in SQL statements

Hi,
I am looking for for a way to set a variable which will be referenced several times within a UNION query.
Something like:
Var=3
SELECT * FROM VIEW_1 WHERE FIELD_1 = Var
UNION
SELECT * FROM VIEW_2 WHERE FIELD_1 = Var
UNION
SELECT * FROM VIEW_3 WHERE FIELD_1 = Var
Instead of something like:
SELECT * FROM VIEW_1 WHERE FIELD_1 = 3
UNION
SELECT * FROM VIEW_2 WHERE FIELD_1 = 3
UNION
SELECT * FROM VIEW_3 WHERE FIELD_1 = 3

I'm sure that for this you were requiring a database solution and not a sqlplus solution ? If so, then you have a couple of options:-
1) change the Var to a function call and have the function return a packaged variable or value in a lookup table that you can set as you require [ i.e. WHERE FIELD_1 = your_function ].
2) use an application context, such that you set an attribute within the context and use it within the view [ i.e. WHERE FIELD_1 = SYS_CONTEXT( 'your_context', 'your_attribute' ) ].
In both methods, you will need to set the value of your variable before referencing the view. The view therefore becomes "parameterised" in this sense.
It might be possible that your view is mergeable. By this I mean that Oracle might be able to push a predicate against the view inside it instead, such that Oracle rewrites this:-
SELECT <cols>
FROM your_union_view
WHERE field_1 = 3;
...and takes that value of field_1 = 3 and "pushes" it into your_union_view itself, in which case you will not need to worry about any of the above solutions. You can test this out by removing the where clauses from your view definition and running an explain plan against a query of the form above. If you see a "VIEW" step in the results, then the view is not mergeable in its current form and you should revert to the methods I listed.
Regards
Adrian
For this you can use application contexts

Similar Messages

  • Using bind variables with sql statements

    We connect from a VB 6.0 program via OO4O to an Oracle 8.1.7 database, using bind variables in connection with select statements. Running ok, but performance again by using bind vars not as good as expected!
    When looking into the table v$sqlarea, we were able to detect the reason. We expected that our program submits the sql statement with bind vars, Oracle parses this once, and with each select statement again, we do not have a reparse. But: It seems that with each new session Oracle reparses the sql statement, that is, Oracle is not able to memorize or cache bind vars and statements. Even more worrying, this kind of behaviour was visible with each new dynaset, but the same database/session.
    Is there anybody our there with an idea of what is happening here?
    Code snippet:
    Dim OraSession As OracleInProcServer.OraSessionClass
    Dim OraDatabase As OracleInProcServer.OraDatabase
    Set OraSession = CreateObject("OracleInProcServer.XOraSession")
    Set OraDatabase = OraSession.OpenDatabase(my database", "my connect", 0&)
    OraDatabase.Parameters.Add "my_bind", 0, ORAPARM_INPUT
    OraDatabase.Parameters("my_bind").DynasetOption = ORADYN_NOCACHE
    OraDatabase.Parameters("my_bind").serverType = ORATYPE_NUMBER ' Bind Var Type
    Dim RS As OracleInProcServer.OraDynaset
    strSQLstatement= "Select * from my_table where igz= [my_bind] "
    Set RS = OraDatabase.CreateDynaset(strSQLstatement, &H4)
    OraDatabase.Parameters("my_bind").Value = myValue
    RS.Refresh
    Cheers and thanks a lot :)
    Michael Sonntag

    We connect from a VB 6.0 program via OO4O to an Oracle 8.1.7 database, using bind variables in connection with select statements. Running ok, but performance again by using bind vars not as good as expected!
    When looking into the table v$sqlarea, we were able to detect the reason. We expected that our program submits the sql statement with bind vars, Oracle parses this once, and with each select statement again, we do not have a reparse. But: It seems that with each new session Oracle reparses the sql statement, that is, Oracle is not able to memorize or cache bind vars and statements. Even more worrying, this kind of behaviour was visible with each new dynaset, but the same database/session.
    Is there anybody our there with an idea of what is happening here?
    Code snippet:
    Dim OraSession As OracleInProcServer.OraSessionClass
    Dim OraDatabase As OracleInProcServer.OraDatabase
    Set OraSession = CreateObject("OracleInProcServer.XOraSession")
    Set OraDatabase = OraSession.OpenDatabase(my database", "my connect", 0&)
    OraDatabase.Parameters.Add "my_bind", 0, ORAPARM_INPUT
    OraDatabase.Parameters("my_bind").DynasetOption = ORADYN_NOCACHE
    OraDatabase.Parameters("my_bind").serverType = ORATYPE_NUMBER ' Bind Var Type
    Dim RS As OracleInProcServer.OraDynaset
    strSQLstatement= "Select * from my_table where igz= [my_bind] "
    Set RS = OraDatabase.CreateDynaset(strSQLstatement, &H4)
    OraDatabase.Parameters("my_bind").Value = myValue
    RS.Refresh
    Cheers and thanks a lot :)
    Michael Sonntag

  • Can we use repository variables in SQL statement of column prompt?

    Hi Dudes,
    Below is the query
    SELECT "- End Date"."End Fiscal Year" FROM "Consumer Sector" WHERE ("- End Date"."End Fiscal Year" = valueof (current_year)) or ("- End Date"."End Fiscal Year" = valueof (current_year) -1)
    when use this sql in criteria prompt getting error.
    Please suggest .
    thanks.sri

    Make sure your syntax is correct it should be like VALUEOF("CURRENT_YEAR")-1
    If you still have issues then VALUEOF("CURRENT_YEAR")-1 cast it to int before you subtract.
    If helps pls mark as correct else let share error message

  • Using Bind variables in SQL PLUS Report

    using Bind variables in SQL PLUS Report. This report gets the arguments from the application concurrent program. Now my need is to convert the start_date and end_date to bind Variables to improve the performance. I have commented the original code in 'prompt List of Unapproved Adjustments' and used my Bind Variable but it is giving an error
    error: Bind Variable "ENDING_DATE" not declared
    Report Date and Time:
    26-OCT-2010 15:44:13
    List of Unapproved Adjustments
    Bind Variable 'ENDING_DATE" not declared
    Please see below the code for the sql plus report:
    define p_org_id           = '&1'
    define p_fy_begin_date = '&2'
    define p_start_date = '&3'
    define p_end_date = '&4'
    define p_conversion = '&5'
    declare
    variable begin_date date;
    exec :begin_date := p_start_date;
    variable ending_date date;
    exec :ending_date := p_end_date;
    /* Begin
    :begin_date := to_date('&p_start_date','YYYY/MM/DD HH24:MI:SS');
    :ending_date := to_date('&p_end_date','YYYY/MM/DD HH24:MI:SS');
    End; */
    set newpage none
    set termout off
    set pagesize 55
    set linesize 180
    set heading on
    set feedback off
    set wrap off
    set space 1
    set heading on
    begin
    dbms_application_info.set_client_info('&p_org_id');
    end;
    prompt
    prompt Report Date and Time:
    prompt ----------------------
    select to_char(sysdate,'DD-MON-YYYY HH24:MI:SS')
    from dual ;
    prompt
    prompt List of Unapproved Adjustments
    prompt -------------------------------
    select b.trx_number,
    a.adjustment_number,
    f.user_name created_by
    from apps.ar_adjustments a,
    apps.ra_customer_trx b,
    apps.fnd_user f
    where a.customer_trx_id = b.customer_trx_id
    and a.status <> 'A'
    and a.created_by = f.user_id
    and a.creation_date between :begin_date
    and :ending_date
    -- and a.creation_Date between to_date('&p_start_date','YYYY/MM/DD HH24:MI:SS')
    -- and to_date('&p_end_date','YYYY/MM/DD HH24:MI:SS')
    order by
    b.trx_number ;

    Hi
    Please go to customization part of the report and verify..You have set a default value out there ..And also verify your lov and look at the values ..If it is again giving you the problem ..pl delete the report and develop it again from the scratch it will be solved...
    vishnu
    null

  • Using Collection in a sql statement.

    Hi I want to perform the following statement:
    DELETE FROM ALLOCATION_ELEC_MATRIX
    WHERE dgo_ean_id in (lt_inter_dgos);
    The collection lt_inter_dgos holds my dgo_ean_id's(varchars).
    I can't find a way to get it to work.
    The collection is declared as follows:
    TYPE Interface_param_dgos IS TABLE OF VARCHAR2(20);
    lt_inter_dgos Interface_param_dgos := Interface_param_dgos();
    then later on the collection gets filled. But how can i get it to work to use it in my sql statement?
    I don't won't to use a for loop around it since it would give me problems if I use more collections with a different amount of values in it.

    The standard approach is to use SQL collection type and table function,
    for example
    SQL> create TYPE Interface_param_dgos IS TABLE OF VARCHAR2(20);
      2  /
    Type created.
    SQL> create or replace package my_pkg
      2  is
      3   lt_inter_dgos Interface_param_dgos := Interface_param_dgos();
      4   function get_coll return Interface_param_dgos;
      5  end;
      6  /
    Package created.
    SQL> create or replace package body my_pkg
      2  is
      3   function get_coll return Interface_param_dgos
      4   is
      5   begin
      6    return lt_inter_dgos;
      7   end;
      8  end;
      9  /
    Package body created.
    SQL> begin
      2   my_pkg.lt_inter_dgos.extend(3);
      3   my_pkg.lt_inter_dgos(1) := 'SMITH';
      4   my_pkg.lt_inter_dgos(2) := 'KING';
      5   my_pkg.lt_inter_dgos(3) := 'ALLEN';
      6  end;
      7  /
    PL/SQL procedure successfully completed.
    SQL> select ename from emp;
    ENAME
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    14 rows selected.
    SQL> delete from emp where ename in (select column_value from table(my_pkg.get_coll));
    3 rows deleted.
    SQL> select ename from emp;
    ENAME
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    11 rows selected.Rgds.

  • PL SQL using variable in SQL statement

    I am trying to execute several sql statements, that have the same format but different values. Does this
    mean I need a bind variable?
    ie
    select TO_CHAR ( (SYSDATE - 2), 'YYYY_MM_DD') from dual
    select TO_CHAR ( (SYSDATE - 4), 'YYYY_MM_DD') from dual
    select to_char(add_months(sysdate,-2*1) from dual
    When I try to put the values into a varaiable (date, varchar2 or number) I am getting a conversion
    error.
    Can somebody show me an example of how to do something like this? Or at least point me to the correct
    part of the documentation that provides and example. Pardon my syntax as I know it is incorrect
    val :=add_months(sysdate,-2*1
    select to_char(val) from dual
    Thanks in advance to all who answer

    Hi,
    840386 wrote:
    I am trying to execute several sql statements, that have the same format but different values. Does this
    mean I need a bind variable?No, you don't need a bind variable, though bind variables may be more efficient than using PL/SQL variables. I don't see where you're trying to use any varibables at all in your examples. Is it in place of the literals, such as 2 or 'YYYY_MM_DD'? You can use either bind varibales or PL/SQL variables in those places.
    ie
    select TO_CHAR ( (SYSDATE - 2), 'YYYY_MM_DD') from dual
    select TO_CHAR ( (SYSDATE - 4), 'YYYY_MM_DD') from dual
    select to_char(add_months(sysdate,-2*1) from dualIn PL/SQL, when you have a SELECT statement, you must specify what you want to do with the results. For example, a SELECT ... INTO statement:
    SELECT  AVG (sal)
    INTO    avg_salary
    FROM    scott.emp;There's usually no point in SELECTing from dual in PL/SQL. It's not an error, but it's simpler just to use an assignment statement.
    When I try to put the values into a varaiable (date, varchar2 or number) I am getting a conversion
    error.Post a complete procedure or anonymous block, including variable declarations, that shows exactly what you're trying to do.
    >
    Can somebody show me an example of how to do something like this? Or at least point me to the correct
    part of the documentation that provides and example. Pardon my syntax as I know it is incorrect
    val :=add_months(sysdate,-2*1Assuming val is a DATE, that's basically correct. You have unbalanced parentheses (there's a '(', but no matching ')' ), and you need a semicolon (';') at the end of the statement. Perhaps ');' just got cut off when you were posting this.
    select to_char(val) from dualAgain, SELECTing from dual is unnecessary, but if you had some way to catch the returned value, that would work.
    Usually, the reason why you need to call TO_CHAR is that you want a value in a particular format, which is specified in the 2nd argument to TO_CHAR. Calling TO_CHAR with only one argument is a possible mistake, but not something that would raise an error.
    Here's an example that works:
    SET     SERVEROUTPUT     ON
    DECLARE
         d     DATE;
         v     VARCHAR2 (30);
    BEGIN
         d := ADD_MONTHS (SYSDATE, -2);          -- -2 = (-2*1)
         v := TO_CHAR (d, 'DD-Mon-YYYY');
         dbms_output.put_line (v || ' = v');
    END;
    /Output (when run on March 13, 2011):
    13-Jan-2011 = v

  • Use variable in SQL statement

    HI guys:
    I need code three SQL statements.the returned field and selected table are all same,there is only a difference in their "where" statement.
      Sample code:
        select marcmatnr marcwerks
        into table it_data
        from MARC inner join MBEW on marcmatnr = mbewmatnr
        where marcmatnr like 'A%' and mbewzplp1 = '001'.
        second one........................ mbew~zplp2 = '001'
        third one......................... mbew~zplp3 = '001'
      Could I write a FORM gather them with transporting a parameter ZPLPX to determine which condiniton will be execute?
    thank you very much.

    Hi tianli,
    1. source text
       This concept of dynamic where
       condition is called source text.
    2. use like this.
       This is important in the code  --->  WHERE (mywhere).
    REPORT abc LINE-SIZE 80.
    DATA : it_data LIKE TABLE OF mara WITH HEADER LINE.
    QUOTES ARE IMPORTANT
    PERFORM mysql USING 'mbew~zplp2 = ''001'''.
    FORM mysql USING mywhere.
      SELECT marcmatnr marcwerks
      INTO TABLE it_data
      FROM marc INNER JOIN mbew ON marcmatnr = mbewmatnr
      WHERE (mywhere).
    ENDFORM.                    "mysql
    regards,
    amit m.

  • Using a variable in SQL to store intermediate results

    I'm new to Crystal Reports, so pardon my ignorance.
    I need to write a SQL statement in Crystal Reports (Ver. 11) that uses results from a query and stores them in a variable for further use in the statement. Something like this:
    DECLARE @my_variable INT;
    SET @my_variable=
    CASE
                    WHEN DATEPART (m,{?Date})<7
                    THEN DATEPART (yyyy,( DATEADD (year,-1, {?Date})))
                    ELSE DATEPART (yyyy,( DATEADD (year,0, {?Date})))
    END
    (Where {?Date} is a date parameter)
    Is it possible to achieve this in the above form or some other form in Crystal Reports?
    Thanks

    Simple answer... When I used the variable, I marked it as a string.  There is an email address setting.

  • Using Date objects in SQL statements

    Hi, I am wondering if it is possible to use Date objects while trying to retrieve entries from an access database with fields set as "Date/Time" fields, as opposed to "Text"? If so, do I need to reformat it before inserting it into the SQL statement, or can I just leave it as a Date object, and call up the variable name?
    For example - "SELECT * FROM database WHERE startDate = ' " + dateObject + ' ". And do i need quotes round this value?
    Thanks in advance.

    I had some problems by just fetching a date and pushing it back to a MS SQL Database.
    I used the following reformating step to fix it:
    if (o instanceof Timestamp)
    String time = o.toString().substring(8,10)+"."+o.toString().substring(5,7)+"."+o.toString().substring(0,4)+" "+o.toString().substring(11,19);
    ht.put(columnName, time);
    o is the object i receve from the select statement and ht is a Hashtable where i put my data.
    To write the data back i now can use:
    UPDATE table SET columnname = 'valueOfColumn'
    This means i use the value i created above in Quotes to write it back.
    Format of Timestamp.toString() is something like yyyy-mm-dd hh:mm:ss.xx
    Format used by MS SQL (and i think by Access to) 'dd.mm.yyyy hh:mm:ss'

  • Can we use if/else in sql statement?

    Hi,
    Is it possible to write a sql statement like the one below (not plsql)?
    if (select 'True' from dual) = 'True' -- 1
    then
    select 'True' from dual;  -- 2
    else
      select 'False' from dual; -- 3
    endBasically, I want to execute either sql 2 or 3 based on the result of sql 1. I'm not sure if this is possible using only sql and not having to write a stored proc.
    What are the different ways I can implement this?
    Thanks for the help.

    Billy  Verreynne  wrote:
    The case syntax is a bit funny though as there's not a single condition evaluation (like a DECODE or case structs from some other languages).
    This is what I would expect a typical case struct to look like - evaluating a single condition:
    case <condition>
    when <value-1> then return <result-1>
    when <value-n> then return <result-n>
    else
    return <return-z>
    end
    ?:| You mean like this...?
    SQL> ed
    Wrote file afiedt.buf
      1  select empno, ename, deptno
      2        ,case deptno
      3           when 10 then 'This is Department 10'
      4           when 20 then 'And department 20'
      5           when 30 then 'And of course department 30'
      6         else
      7           'Blimey it is something else!'
      8         end as dept_desc
      9* from emp
    SQL> /
         EMPNO ENAME          DEPTNO DEPT_DESC
          7369 SMITH              20 And department 20
          7499 ALLEN              30 And of course department 30
          7521 WARD               30 And of course department 30
          7566 JONES              20 And department 20
          7654 MARTIN             30 And of course department 30
          7698 BLAKE              30 And of course department 30
          7782 CLARK              10 This is Department 10
          7788 SCOTT              20 And department 20
          7839 KING               10 This is Department 10
          7844 TURNER             30 And of course department 30
          7876 ADAMS              20 And department 20
          7900 JAMES              30 And of course department 30
          7902 FORD               20 And department 20
          7934 MILLER             10 This is Department 10
    14 rows selected.

  • SAP Personas  - Use of variable in IF statement

    Hope someone can assist with this script
    I am storing a value from a dropdown box in a variable so this can be used latter when I am in a different screen within same script.
    But the problem I am facing is if i perform a if statment against a variable , it does not work
    What I do in test script
    1) copy value from drop down into varable
    2) paste value to textbox to test value
    3) if check is equal for value (N506) in variable "site"
    4) if true, put "tested ok" in text box.
    if perofrm the test on the dropdown box directly...  it works
    if perform the test on the textbox i copied variable to... it works.
    if perform test on variable directly...it fails...
    Doing the test in the first two cases, will not work , as the textbox and dropdown box will not be on screen , when i need to perofm the if statement.
    I am suspecting the if statement is interpurting the word site, as a text rather then a varaible name, so how can  read a variable and use it in a if statement, without using a box on the screen itself.
    Any help is appreciated.

    thanks Tamas....   i knew it was something simple...  code works great now.

  • Using cursor function in sql statement

    hi all
    can anyone plss explain why and when we will use cursor function in a sql statement like this and what is the difference while executing this sql statement with cursor function in comparison of a simple sql statement----
    select
    department_name,
    cursor (
    select last_name
    from employees e
    where e.department_id = d.department_id
    order by last_name
    ) the_employees
    from departments d
    thnx in advance

    RTFM
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/sqloperations.htm#sthref1452
    Cheers
    Sarma.

  • Using 1 = 1 in SQL Statements

    I have just been told by our DBA that we have to go through
    our code and remove the "WHERE 1 = 1" in our SQL statements on a
    SQL 2000 database. He said it is a performance issue when nothing
    else follows it (no AND's).
    For example (the wrong way):
    SELECT this_ID FROM thistable WHERE 1 = 1
    Versus...
    SELECT this_ID FROM thistable WHERE 1 = 1 AND this_ID = 1001
    He said Microsoft said that this is causing a performance hit
    when there is no AND clauses after the WHERE.
    Some of these SQL statements are pretty big and there is no
    practical way to do a CFIF beforehand.
    Has anyone heard of a performance hit like this? If so, how
    much of a hit? The main table in the DB has about 2 million records
    with full text indexes.
    Thanks,
    Rob in Tampa

    Phil,
    Thanks for the speedy response. I forgot to mention.. there
    are TOP 200 clauses in all the big SQL statements.
    And, like I said before... some of the queries are too big to
    test to see if at least 1 of the condidtions exsist. More often
    than not, the WHERE 1 = 1 clause will not be alone. I personally
    think it is a pet peeve of the DBA where he doesn't see any use of
    the 1 = 1. He said.. it's always going to be true. Kinda the point
    of having it.
    This was taught to me years ago.. but, this is the biggest
    application I have worked on where SQL performance could be an
    issue. It was mentioned that the hit comes when SQL Server is
    building its execution plan and has to include the WHERE 1 = 1
    clause. How much of a hit can it cause? Most of the empty clauses
    with no AND's are most likely in a JOIN clause or something.
    The WHERE placeholder is in almost all of our queries in one
    way or another. Not a small project.
    Thanks,
    Rob

  • NDS : how to use a ' in the sql statement ?

    Hi folks,
    I would like to use a sql statement which includes single quotes "'" into my NDS statement.
    Since I have to put my statement into a varchar within single qutes I have to
    mark the internal quotes as quotes which have to be in my varchar buit don't effect the quoting of the whole varchar.
    How can I do that ?
    Best regards,
    Daniel

    I got it. In order to distinguish between data single quote and varchar sigle quote, you need to use 2 single-quotes instead of one in DATA.
    Like this.
    SQL>
    SQL> drop table table1;
    Table dropped.
    SQL>
    SQL> create table table1(col1 varchar2(20));
    Table created.
    SQL>
    SQL> insert into table1 values('Sarma''s');
    1 row created.
    SQL>
    SQL> commit
      2  /
    Commit complete.
    SQL> select * from table1
      2  /
    COL1
    Sarma's
    SQL> Cheers
    Sarma.

  • Bind Variables in SQL Statement

    can someone tell me if there is a way to find out what the bind variables values are in an sql statement extracted from any of the v$sql or v$sqlarea type tables ?
    sql example:
    update DTree set OriginOwnerID=:A
    where OriginOwnerID=:B and OriginDataID=:C
    Thanks
    Jim

    Hi damorgan
    i see two ot of the three:
    SQL> desc gv$sql_bind_capture
    ERROR:
    ORA-04043: object gv$sql_bind_capture does not exist
    i just trying to see what bind variable values would be associated with the sql when i extract the sql from v$sql and if that is even possible
    Thanks
    Jim

Maybe you are looking for

  • How do I edit a WordPress site in Dreamweaver?

    I found a pretty good article on how to install WordPress to a localhost and run a site made locally on a test server through Dreamweaver (http://www.adobe.com/devnet/dreamweaver/articles/dw_wordpress_pt1.html), but it leaves a lot unanswered. Like..

  • VC Change username and password for web services

    Hi everybody I need to change the username and password into the portal of some web services that   have already been created portal is consuming these web services  a XI Thansk Ivan

  • Video Podcast RSS

    http://www.joshuabartholomew.com/JB/index.html I have made a Podcast Home page, I've created 14 entries, but when I subscribe to my feed or try to add the podcast to iTunes, there are no episodes. The strange thing is that I can view the videos on ea

  • How to change the SID during system copy

    This blog /people/johannes.heinrich/blog/2006/07/07/new-features-in-db2-udb-v9--part-3 (i.e.  the "new feature of V9" in this group) only talk about the system copy without changing the SID. In reality, we often want to change the SID during the syst

  • Problem of ipad with PC

    My PC with Windows XP SP2 is recognizing my ipad as digital camera only. How can I overcome this problem?