Dinamic query

Hello!
For first, sorry for my ignorance, but I'm not DBA and who is DBA at my company couldn't help me (I don't know why!).
I have a problem with dinamic filters in some queries.
I want to select N rows of a table, but the query can vary in a series of filters, it depending on the parameters.
For example:
first case:
SELECT X FROM TABLE
WHERE X = 'TEST';
second case:
SELECT X FROM TABLE
WHERE X = 'TEST'
OR X = 'AAA';
Did you understand? This is the problem. How can I concatenate this clause "OR" in the end of the query when I want, without create it as a string and using "EXECUTE SQL"...?
I want to use it as a dinamic command...
One more time, sorry if this is a question that only fools do. I'm learning by myself, and at the moment I'm lost. =)
Thanks!

in this case performance problem occurs for the NULL case only?
create table tab (x varchar2(16));
insert into tab values ('TEST');
insert into tab values ( NULL );
begin
   for i in 1..1000000 loop
       insert into tab values ( to_char(i) );
   end loop;
end;
create unique index ui_tab_x on tab(x) nologging;
exec dbms_stats.gather_table_stats(user, 'tab');
commit;
set timing on
set autotrace traceonly
SELECT X FROM tab WHERE X = 'TEST' or X = DECODE(1,NULL,X,1) ;
Elapsed: 00:00:00.00
Execution Plan
Plan hash value: 3421616299
| Id  | Operation          | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT   |          |     2 |    12 |     4   (0)| 00:00:01 |
|   1 |  CONCATENATION     |          |       |       |            |          |
|* 2 | INDEX UNIQUE SCAN| UI_TAB_X | 1 | 6 | 2 (0)| 00:00:01 |
|* 3 | INDEX UNIQUE SCAN| UI_TAB_X | 1 | 6 | 2 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access("X"='TEST')
3 - access("X"='1')
Statistics
          1  recursive calls
          0  db block gets
6 consistent gets
          0  physical reads
          0  redo size
        444  bytes sent via SQL*Net to client
        384  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          2  rows processed
SELECT X FROM tab WHERE X = 'TEST' or X = DECODE(NULL,NULL,X,NULL) ;
1000001 rows selected.
Elapsed: 00:00:05.87
Execution Plan
Plan hash value: 1995730731
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT  |      |     1 |     6 |   503   (9)| 00:00:07 |
|* 1 | TABLE ACCESS FULL| TAB | 1 | 6 | 503 (9)| 00:00:07 |
Predicate Information (identified by operation id):
1 - filter("X"="X" OR "X"='TEST')
Statistics
          1  recursive calls
          0  db block gets
68353 consistent gets
          0  physical reads
          0  redo size
   16555973  bytes sent via SQL*Net to client
     733710  bytes received via SQL*Net from client
      66668  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
    1000001  rows processedwhat is your Oracle version? I did above test on 10gR2. And are you using bind variables for this operation?
if you are using bind variables force the NOT NULL cases to be parsed differently than NULL case, so guarantee for different execution plans no matter which comes first.
one way to do this can be with an if block and use comments in your code.
if arg is NOT NULL then
   select /* NOT null case */ X FROM tab WHERE X = 'TEST' or X = DECODE(arg,NULL,X,arg) ;
else
   select /* null case */ X FROM tab WHERE X = 'TEST' or X = DECODE(arg,NULL,X,arg) ;
end if;  

Similar Messages

  • Dinamic Query SQL injection

    I would like to do a dinamic query. I dont know the number of columns of the column and the table, and things like that. I�m worried about sql injection how can i avoid it.
    For example,
    select column1,column2,....
    from tabla
    where column1=columna2 and...
    I know the format i must build it with Java.

    PreparedStatement can avoid most of the standard SQL injection attacks. However, you should not allow a client to request arbitrary SQL statements to be executed unless you have some serious security in your network and are behind a very good firewall.
    - Saish

  • Dinamic query on 8.0.5 db

    Hi.
    I4m traying to make a dinamic query as:
    "select ec_ctnt.filename
    from ec_ctnt, ec_prditm_ctntlst
    where ec_ctnt.ctntid = ec_prditm_ctntlst.ctntid and ec_prditm_ctntlst.prditmid = ?" using thin jdbc driver, but compiling it with JDeveloper obtain the error messaege "ORA-01008: Not all variables bound", but I include the CalledStatement.setInt() method after this line.

    It appears you are using a PreparedStatement object for your query, in which case you need to use the prepared statement object's setInt(int parameterIndex, int x) method.
    For example:
    PreparedStatement pstmt = conn.prepareStatement("... = ?");
    pstmt.setInt(1, <somenumber>);
    null

  • Dinamic Query Rowtype

    Hi:
    Anybody know how get Rowtype from one dinamyc Query like this
    lc_SQL := 'SELECT';
    For i in 1 ... N LOOP
    lc_SQL := lc_SQL || Fieldi;
    END LOOP;
    OPEN Cursor FOR lc_SQL;
    FETCH Cursor BULK COLLECT INTO xxxxxx
    How I can know rowtype from Cursor to asign into xxxxxx

    You can't get this information dynamically.
    Dynamic SQL is mainly useful for varying the WHERE clause. As it happens we can also vary the names of the columns and even the tables we select from. But we cannot vary the signature of the query. The datatype structure and name(s) of the receiving variable (array, record, whatever) have to be fixed. Otherwise nothing will compile.
    The workaround is to use DBMS_SQL which does support some metadata functionality. However, the only way to make the receiving variable dynamic is code your entire program in a dynamic fashion. Which way madness lies.
    The other approach is to use objects. You could frame your dynamic select statements as casts to object types and select into an array of ANYTYPE. Of course, you would have to declare your TYPEs in DDL beforehand so it's not very dynamic. In fact, forget about it.
    Essentially, PL/SQL is a strongly typed, non-reflective language. Deal with it. If you want weak (i.e. runtime) type casting (and the concomitant performance hit) use Python.
    Cheers, APC

  • How to dump a query on a XLS file?

    I´m working in a stored procedure on that i can send a dinamic query and it return me the result into a xls file.
    I´ve found the way to generate that xls file from Pl/sql, but now I need be able to assing each field of each row into his corresponding cell. For this I need to put each field of each row in a variable and then work on it.
    For generate xls file, I´ve created a datatype by following the indications of Jasson Bennet´s blog.
    http://radio-weblogs.com/0137094/2006/10/26.html
    In the example, values are assigned directly to the cells. But it not is valid for me because I dont know what will be these...
    I think that if you want see the blog, you´ll can understand better what I´m refering...
    Thanks for your time...

    Strange requirement, you don't know the query, the columns and the number of rows you get, but you know that you want the value of the second column of the second row :)
    But try this
    declare
      t_c integer;
      t_r integer;
      t_v varchar2(100);
    begin
      t_c := dbms_sql.open_cursor;
      dbms_sql.parse( t_c, q''select 'Roy' name, 'sales' deptno, 25 age from dual
    union all select 'Sara', 'HHRR', 30 from dual
    union all select 'Mike', 'finances', 35 from dual'', dbms_sql.native );
      dbms_sql.define_column( t_c, 2, t_v, 100 );
      t_r := dbms_sql.execute( t_c );
      t_r := dbms_sql.fetch_rows( t_c );
      t_r := dbms_sql.fetch_rows( t_c );
      dbms_sql.column_value( t_c, 2, t_v );
      dbms_sql.close_cursor( t_c );
      dbms_output.put_line( t_v );
    end;
    /

  • How to make a search in a form

    Hi
    I have a form with a lot of items(name date,age,height) that i can use to make a search . I found many problems for the search , infact i had to create many cursors, one for each case. For example i would search for age and height or just from date and so on.
    How can i make it more easy?
    Can i use a dinamically query for a cursor ?
    PLZ HELP

    if you don't use oracle default search buttons, then you may code your own search buttons, inside, you may ,
    e.g., user might want to enter height and age fields(Assume the table columns are HEIGHT and AGE),
    then use,
    IF :heightitem is not null then
    w_str := ' AND HEIGHT ='||:heightitem;
    END IF;
    IF :AGEITEM IS NOT NULL THEN
    w_str := w_str||' AND AGE='||:ageitem;
    END IF;
    then you set_block_property('..',default_where,w_str); then execute_query. In order to avoid giving user blank form fields when no records found, which oracle did this badly, then you may use SELECT COUNT(*) into cnt FROM ... WHERE ...w_str to detect the cnt, if cnt > 0 then execute_query, if not, then shoot no record data found message out.

  • Query data dinamically

    I want to execute a query that it is formed dinamically based in some text items that I have in the form; I want to use the Execute Query button on the default toolbar. My question is how to pass the text item content as a parameter to the where clause in datablock property field?
    Thanks

    Hello
    you can use the SET_BLOCK_PROPERTY procedure for both the where clause or an order by.
        v_WHERE := F_SET_WHERE;     -- construct your where clause in a function
        GO_BLOCK ( <my_block> );
        CLEAR_BLOCK ( NO_VALIDATE );
        SET_BLOCK_PROPERTY ( <my_block>, DEFAULT_WHERE, v_WHERE );
        EXECUTE_QUERY;Bernd

  • IS IT POSSIBLE TO CHANGE DINAMICALLY THE SOURCE OF A QUERY?

    IS IT POSSIBLE TO CHANGE DINAMICALLY THE SOURCE OF A QUERY, AND TO SHOW DATA FROM DIFERENT TABLES, BASED IN USER PARAMETER VALUE?.
    EXAMPLE:
    IF USER PARAMETER = 1 THEN
    SELECT COLUMN1 FROM TABLE1
    ELSIF USER PARAMETER = 0 THEN
    SELECT COLUMN2 FROM TABLE2
    END IF;
    ANY OTHER IDEA??
    THANKS FOR HELPS.

    Read the online help about lexical parameters.
    Select a from &p_1
    should work.

  • How to input several queries at once in a text field, query from it?

    Hi ,
    I am starting out in oracle development and am currently attempting to develop a tool which uses a text item which can be updated by cut and paste (~ie from a spreadsheet) and then can query several tables(each as blocks joined by relations with the primary key of the first block being that of each item in the text feild) pulling back one row for each item entered in the original text item and displaying all the results as usual in the joined data fields. The problem i am having is attempting to 1. inserting multiple data items into the query box (text item), as the focus stays in the first item and i want to insert say 20 for the query by cut and paste. Secondly when populated i want to be able to use all these items to query the database when i press a button , however it shall only query the first row in the text item . Is it possible to loop in a when button pressed trigger? If not then i thought about inserting the rows in the original text item into a database table then joining it to the other tables by relation for query, however how do i loop through the text time and insert into a table( in a trigger or in a called procedure? any help would be much appreciated.

    Hi
    I am not sure if I understood completely what you want to do,
    but if you want to query a block using a list of values,
    you can modify dinamically the block where clause and use
    the operator "in".
    For example, loop through the values in the text item and
    build a list of values - at the end you'll get in a varchar2
    variable the following:
    '10, 12, 17, 22'
    Let's say the variable is called vList. Then you can use:
    set_block_property('myblock', default_where, 'thecolumn in ('||vList||')');
    So the block will retrieve all and only the records in the list.
    By the way, I suggest you break such long posts with blank lines
    between the paragraphs, it's easier to read!

  • Determine context value dinamically

    Hi Gurus,
    I have to develop a report where as input value the user sets the year and in the columns we have the calendar week and in rows several KFs.
    Let say we have KF1 and KF2. KF1 is a ratio from the underlying infoprovider, Sales volume. KF2 is the average of KF1 for the last 4 weeks(not including the one in context).
    So my concern is how could I determine dinamically the value for the week in the context of the calculation so I can get the values for previous weeks. Here you have an example:
    Calendar week     2     3     4     5                         6 ......
    Actual Sales           200  300  400   500                     250
    Avg. actual sales
    last 4 weeks                                         ((200 + 300 + 400 + 500) / 4) = 350
    Thanks a lot in advance!

    I´ve tried using four hiden ratios and restricting them using a replacementh path variable defined over the calendar week but it does not allow me to replace by the value of the characteristic. It only allows to do the replacement by a query or another variable.

  • How to restrict records in Infoset query

    Hi Friends,
      I have created an Infoset & a query based on this infoset. I would like to restrict certain records being displayed, based on field value, say if field A = 'Blank' I do not want to see this record on the Bex report.
    Please let me know if this is possible at all.
    Thanks,
    JB

    Hi,
    if you want to restrict a report based on a characterristic value you have to:
    1)Open the query in design mode
    2)Insert the characteristic in your report (in this example field "A")
    3)Double clikc in the characteristic
    4)You will see 2 tabshett, here you have the option to restrict in a estatic (using a fix value) or dinamic value (usign variable)
    5)For example use static value, select the desire value and then OK
    6)Save
    7)Execute.
    Regards
    Asign points if useful please

  • Date format mask in Enter-Query mode

    Hi,
    I'm developing a Form which is able to query the masterblock from a detail-item.
    The queryable detail-item is a date field and has a datatype: DATETIME. When a new record is entered the values in the date field are stored in the database like "18-10-2002 15:04:02"
    When the form is in enter_query mode the user must be able to enter 18-10-2002 (DD-MM-YYYY format mask, so without time mask). When execute the query with this date format the query is not able to find data.
    I used a Key-Execute-Query on the detailblock like this:
    SELECT 1.COLUMN
    , 2.COLUMN
    INTO :1.COLUMN
    , :2.COLUMN
    FROM TABLE.1
    , TABLE.2
    WHERE 1.COLUMN = 2.COLUMN
    AND TO_CHAR(1.COLUMN,'dd-mm-yyyy') = to_date(:avg.datum,'dd-mm-yyyy');
    Can anyone please help me?
    Regards,
    Ronny.

    Hi Ronny,
    I'm not sure to have got exactly your issue (especially why you have to use that select in master-detail query), but I suggest you to substitute
    ...AND TO_CHAR(1.COLUMN,'dd-mm-yyyy') = to_date(:avg.datum,'dd-mm-yyyy');
    with
    ...TRUNC(1.COLUMN) = TO_DATE(:avg.datum,'dd-mm-yyyy');
    To be fair, I would use it in the where clause, even if you set it dinamically.
    Let us know,
    Marco

  • JSF:how to get value from dinamically generated HtmlInputText components�H�H

    <h:panelGroup binding="#{dynamicInputGroupBean.group}"/>
    public HtmlPanelGroup getGroup() {
              if (this.getSelectedComp() == null) {
                   return this.group;
              FacesContext facesContext = FacesContext.getCurrentInstance();
              Application application = facesContext.getApplication();
              this.group = new HtmlPanelGroup();
              Set pSet = this.getSelectedComp().getParameterses();
              int size = pSet.size();
              this.instanceValue = new String[size];
              int i = 0;
              for (Iterator it = pSet.iterator(); it.hasNext();) {
                   Parameters tempP = (Parameters) it.next();
                   HtmlOutputLabel outputLable = new HtmlOutputLabel();
                   HtmlInputText inputText = new HtmlInputText();
                   inputText.setId("p" + i);
                   String valueBindingExpression = "#{dynamicInputGroupBean.instanceValue["+i+ "]}";
                   System.out.println(valueBindingExpression);
                   ValueBinding valueBinding = application
                             .createValueBinding(valueBindingExpression);
                   inputText.setValueBinding("value", valueBinding);
                   outputLable.setFor(inputText.getId());
                   outputLable.setValue(tempP.getParaname() + ": ");
                   group.getChildren().add(outputLable);
                   group.getChildren().add(inputText);
                   i++;
              // group.getChildren().add(new HtmlInputText());
              return group;
         }as codes show above, i successfully genera HtmlInputText dinamicaly�C
    but i got problems while i try to print those values...
    after the the jsp page presents in my browser,
    i input some words in the input components,
    and then click a commandButton hold an action to print their value
    action code :
    String[] tempArray = this.getInstanceValue();
    for (int i = 0; i < tempArray.length; i++) {
    System.out.println(tempArray);
    only NULL has been printed in the consol ....not the word i inputed!!!
    so my question is how can i get values from those
    dinamically generated HtmlInputText ????

    This approach is odd. What's the functional requirement after all? You normally attach the inputtext value to a backing bean property and do the desired command button action which is attached to a backing bean action method. In this method you then use the value for the query.

  • From XML To Query

    Hi,
    This is My problem:
    I receive datas from an xml Feed and I always worked in this
    way:
    <cftry>
    <!--- fetch data from web service --->
    <cfhttp url="
    http://www.............
    method="get" charset="utf-8"/>
    <cfset xmldata = cfhttp.fileContent>
    <cftry>
    <!--- extract data from XML document and convert to query
    --->
    <cfset lstColumns =
    "KH,NH,KC,NC,KD,ND,KS,NS,KL,NL,KZ,NZ,LR"/>
    <cfset q2 = queryNew(lstColumns)/>
    <!--- <cfif isXml(cfhttp.fileContent)> avialable in
    CF7 only --->
    <cfset xmlObject = xmlParse(xmldata)/>
    <cfloop index="i" from="1"
    to="#arrayLen(xmlObject["ArrayOfHotelRoom"].xmlChildren)#">
    <cfset queryAddRow(q2,1)/>
    <cfloop index="ii" list="#lstColumns#">
    <cfset
    querySetCell(q2,ii,xmlObject["ArrayOfHotelRoom"].xmlChildren
    [ii].xmlText)/>
    </cfloop>
    </cfloop>
    <!--- </cfif> --->
    <cfcatch type="any"> <!--- any errors return empty
    result set --->
    <cfset q2 = queryNew(lstColumns)/>
    </cfcatch>
    </cftry>
    <cfcatch type="any">
    <cfoutput>There has been an internal problem. Please
    try again later</cfoutput>
    <cfexit>
    </cfcatch>
    </cftry>
    <!--- use QoQ to filter by hotel name --->
    <cfquery name="q" dbtype="query">
    select * from q2
    where SH = 'A' <!--- only show available hotels --->
    </cfquery>
    NOW THE PROBLEM IS THAT I NEED NOW TO IMPROVE MY SYSTEM USING
    A NEW VERSION OF THE XML CATALOGUE THAT NOW INCLUDE XML.CHILDREN:
    THE NEW XML:
    <?xml version="1.0" encoding="utf-8"?>
    <ArrayOfHotelRoom xmlns:xsd="
    http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="
    http://www.w3.org/2001/XMLSchema-instance"
    xmlns="
    http://tempuri.org/xml/xmlService">
    <HotelRoom>
    <KH>717</KH>
    <NH>Acanto Suites & Lounge</NH>
    <KC>PDC</KC>
    <NC>Playa del Carmen</NC>
    <KD>16</KD>
    <ND>Playa del Carmen</ND>
    <KS>7E</KS>
    <NS>Special Category</NS>
    <KL>CENT</KL>
    <NL>City</NL>
    <KZ>1</KZ>
    <NZ>The Yucatan Peninsula</NZ>
    <LR>132.5000</LR>
    <Rooms>
    <RoomType>
    <KR>VLLBR1</KR>
    <NR>One Bedroom Villa</NR>
    <MP>RO</MP>
    <RR>132.5</RR>
    <IP>0</IP>
    <IL>0</IL>
    <IN>0</IN>
    <IF>0</IF>
    <PH>0</PH>
    <SH>A</SH>
    </RoomType>
    </Rooms>
    </HotelRoom>
    AS YOU SEE AFTER "LR" NOW I FIND OTHERS CHILDREN AND I DO
    NOT HOW TO REDUCE MY NEW XML TO QUERY
    Thank You
    Andrea

    Hi Charlie,
    thanks for your fast answer. I try to figure out what's are
    my doubts and need:
    1) Yes it must to be a query because i need to filter data to
    be shown in many different outputs.
    2) I understand that it should be possible to create
    something like 2 database table :
    one for the Hotel and
    one for Rooms with all the subitems( I confirm you that there
    will be situations with more RoomType Item for each Rooms. My doubt
    now is how I will be able to manage the query joining the 2 tables
    when I miss a common date to show in the statement WHERE ( Example
    : WHERE Hoteltable.#KH#( hotel ID ) = RoomsTable.#Here I will miss
    the compare data that in the second table is not provided by the
    xml#.
    How will I be able to manage the query??????
    I think this is our way but I am really lost at this level.
    Of course the solutions with only one table with multiple
    rows for each rooms type will create me problems in outputs results
    . I will have results where the selection will not be the hotel but
    the rooms type and will be inconvenient to receive dinamically 5
    times the same hotel with the different rooms type details.
    What I need is to receive each hotel only once with all the
    roomstype details inside.
    Thanks for your help
    Andrea

  • Please is possible to create the most common adf components dinamically?

    Or you have some comment or advise?
    I need to create dynamically forms from a definition on tables.
    I don't need but anyway I didn't find a way to create entities dinamically, only views.
    Thank you :)

    I told what are the limitations, I even bought the book oracle jdeveloepr 10g for forms and pl/sql developers to search for similar functionality as there is in Oracle forms.
    in example
    Improvement of help in JDeveloper
    I really have problems understanding adf api
    The first problem is there are no equivalent for oracle forms functionality and jdeveloper api needs more examples, some years ago I saw how some programmers talk about some uses of api as if it were magic or a big discovery, but a good documentation and examples of APi will help every one, now, after more than one years I had seen there are more examples and demos, and people know more than then.
    I'm not talking about new functionality I was talking about the functionality there were in Oracle Forms, not necessary all, but at least some.
    One of many many examples could be how can I get the functionality of COUNT_QUERY built-in when using ADF views.
    In an On-Count trigger, performs the default Form Builder processing for identifying the number of rows that a query will retrieve for the current block, and clears the current block. If there are changes to commit in the block, Form Builder prompts the end user to commit them during COUNT_QUERY processing. Form Builder returns the following message as a result of a valid call to COUNT_QUERY:
    FRM-40355: Query will retrieve <number> records.
    If you could answer this question I really will appreciate it.
    That's the reason then we didn't choose adf to develop web applications, and choose PHP, currently we are thinking in zend framework and php; but we decided to give a check to ADF again.
    Thank you :)

Maybe you are looking for