Exclude duplicate values on SQL where clause statement

Hi!
Are some posibilities to exclude duplicate values do not using sql aggregate functions in main select statement?
Priview SQL statement
SELECT * FROM
select id,hin_id,name,code,valid_date_from,valid_date_to
from diaries
QRSLT
WHERE (hin_id = (SELECT NVL(historic_id,id)FROM tutions where id=/*???*/ 59615))
AND NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy')) <= (SELECT NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy'))FROM tutions where id= /*???*/ 59615)
AND trunc(valid_date_from) >=(SELECT trunc(valid_date_from)FROM tutions where id= /*???*/ 59615)
The result
ID                  HIN_ID    NAME      CODE    VALID_DATE FROM                 VALID_DATE_TO    
50512
59564
RE TU
01
07.06.2013 16:32:15
07.06.2013 16:33:28
50513
59564
TT2 
02
07.06.2013 16:33:23
07.06.2013 16:33:28
50515
59564
TT2 
02
07.06.2013 16:33:28
07.06.2013 16:34:42
50516
59564
ROD 
03
07.06.2013 16:34:37
07.06.2013 16:34:42
VALID_DATE_TO & AND VALID_DATE_FROM tutions
07.06.2013 16:34:42
15.07.2013 10:33:23
In this case i got duplicate of entry TT2 id 50513  In main select statement cant use agregate functions are even posible to exclude this value from result modifying only the QLRST WHERE clause (TRUNC need to be here)
THANKS FOR ANY TIP !
ID.

Hi, Ok this is working in this case
SELECT * FROM
select id,hin_id,name,code,valid_date_from,valid_date_to
from diaries ahs
QRSLT
WHERE (hin_id = (SELECT NVL(historic_id,id)FROM aip_healthcare_tutions where id=/*???*/ 59615))
AND NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy')) <= (SELECT NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy'))FROM tutions where id= /*???*/ 59615)
AND trunc(valid_date_from) >=(SELECT trunc(valid_date_from)FROM tutions where id= /*???*/ 59615)
AND NOT  EXISTS
(SELECT null FROM diaries ahs WHERE  ahs.valid_date_from < QRSLT.valid_date_from
    AND QRSLT.hin_id=ahs.hin_id
    AND QRSLT.code=ahs.code);
Result
50512
59564
RE TU
01
07.06.2013 16:32:15
07.06.2013 16:33:28
50513
59564
TT2 
02
07.06.2013 16:33:23
07.06.2013 16:33:28
50516
59564
ROD 
03
07.06.2013 16:34:37
07.06.2013 16:34:42
But if the Data in tutions row  are theese(valid_date_to-null)  then NO ROWS are returning and its logical because in full result list Valid_date_from column are logical incorect
valid_date_from                                 valid_date_to
15.07.2013 10:33:23
NULL
ID                  HIN_ID    NAME      CODE    VALID_DATE FROM                 VALID_DATE_TO 
50510
59564
RE TU
01
07.06.2013 16:33:28
50511
59564
TT2 
02
07.06.2013 16:34:41
50514
59564
ROD 
03
07.06.2013 16:34:41
50520
59564
Params
04
03.07.2013 21:01:30
50512
59564
RE TU
01
07.06.2013 16:32:15
07.06.2013 16:33:28
50513
59564
TT2 
02
07.06.2013 16:33:23
07.06.2013 16:33:28
50515
59564
TT2 
02
07.06.2013 16:33:28
07.06.2013 16:34:42
50516
59564
ROD 
03
07.06.2013 16:34:37
07.06.2013 16:34:42
Are that posible modifying where statement  if the valid_date_to in tutions are null then theese records where in diary valid_date_to is null is correct to, but need to stay previos logic
D                  HIN_ID    NAME      CODE    VALID_DATE FROM                 VALID_DATE_TO 
50510
59564
RE TU
01
07.06.2013 16:33:28
null
50511
59564
TT2 
02
07.06.2013 16:34:41
null
50514
59564
ROD 
03
07.06.2013 16:34:41
null
50520
59564
Params
04
03.07.2013 21:01:30
null
Thanks !
ID.

Similar Messages

  • Prompted value corrupts SQL WHERE clause - bug?

    Using 10.1.3.4...
    I implemented a simple pivot based request that navigates to a second request when the user drill down on one of the fields. This field is set to "value is prompted" in my second request. (I chose navigate method above drill (dimensions) for a few reasons not really important to this posting, mainly to do with format of requests at different levels)
    All good and the drill down works well, parameters are passed correctly, except then I noticed that totals in my second request doesn't accurately tie back to my first request. After some research I found a very odd reason for this, my WHERE clause is getting corrupted - which almost looks like a bug in OBIEE and were wondering if anybody else has seen this behaviour from OBIEE and know a work around (before I try the Oracle support channels)
    From Answers the request SQL is (I'll highlight the lines getting messed up):
    SET VARIABLE DISABLE_CACHE_HIT = 1;
    SELECT
    BUSINESS_UNIT.Segment saw_0, BUSINESS_UNIT."Business Unit" saw_1, OPPORTUNITY.CLOSEPROBABILITY saw_2, OPPORTUNITY.CLOSEPROBABILITY saw_3, YEAR(OPPORTUNITY.ESTIMATEDCLOSE) saw_4, OPPORTUNITY_ADDON.TCV_IN_USD/1000000 saw_5, OPPORTUNITY_ADDON.WEIGHTED_TCV_IN_USD/1000000 saw_6, CASE OPPORTUNITY.CLOSEPROBABILITY WHEN 100 THEN OPPORTUNITY_ADDON.TCV_IN_USD/1000000 ELSE 0 END saw_7 FROM "Sales"
    WHERE (OPPORTUNITY.STAGE NOT IN ('Lost', 'On Hold')) AND (YEAR(OPPORTUNITY.ESTIMATEDCLOSE) &gt;= YEAR(CURRENT_DATE)) AND
    ((({color:#ff0000}OPPORTUNITY.CLOSEPROBABILITY &gt; 25) AND (TIMESTAMPDIFF(SQL_TSI_MONTH, CURRENT_DATE,OPPORTUNITY.ESTIMATEDCLOSE) &lt;= 4)) OR ((OPPORTUNITY.CLOSEPROBABILITY &gt;= 10) AND (TIMESTAMPDIFF(SQL_TSI_MONTH, CURRENT_DATE,OPPORTUNITY.ESTIMATEDCLOSE) &gt; 4{color})))
    ORDER BY saw_0, saw_1, saw_2, saw_3, saw_4, saw_5, saw_6, saw_7
    Which results in the following SQL request (from NQQuery.log)... The prompted value (BUSINESS_UNIT.Segment) is added correctly to the WHERE clause, but see how the remainder get's changed:
    SQL Request:
    SET VARIABLE QUERY_SRC_CD='Report',SAW_DASHBOARD='/shared/01 - Financials/_portal/4. Pipeline',SAW_DASHBOARD_PG='Pipeline',SAW_SRC_PATH='/shared/01 - Financials/4. Pipeline/Pipeline - Current - T2',DISABLE_CACHE_HIT = 1;
    SELECT
    BUSINESS_UNIT.Segment saw_0, BUSINESS_UNIT."Business Unit" saw_1, OPPORTUNITY.CLOSEPROBABILITY saw_2, OPPORTUNITY.CLOSEPROBABILITY saw_3, YEAR(OPPORTUNITY.ESTIMATEDCLOSE) saw_4, OPPORTUNITY_ADDON.TCV_IN_USD/1000000 saw_5, OPPORTUNITY_ADDON.WEIGHTED_TCV_IN_USD/1000000 saw_6, CASE OPPORTUNITY.CLOSEPROBABILITY WHEN 100 THEN OPPORTUNITY_ADDON.TCV_IN_USD/1000000 ELSE 0 END saw_7 FROM "Sales"
    WHERE (BUSINESS_UNIT.Segment = 'Enterprise') AND (OPPORTUNITY.STAGE NOT IN ('Lost', 'On Hold')) AND (YEAR(OPPORTUNITY.ESTIMATEDCLOSE) &gt;= YEAR(CURRENT_DATE)) AND
    ((({color:#ff0000}OPPORTUNITY.CLOSEPROBABILITY &gt;= 10) AND (TIMESTAMPDIFF(SQL_TSI_MONTH, CURRENT_DATE,OPPORTUNITY.ESTIMATEDCLOSE) &gt; 4)) OR ((OPPORTUNITY.CLOSEPROBABILITY &gt;= 10) AND (TIMESTAMPDIFF(SQL_TSI_MONTH, CURRENT_DATE,OPPORTUNITY.ESTIMATEDCLOSE) &gt; 4{color})))
    ORDER BY saw_0, saw_1, saw_2, saw_3, saw_4, saw_5, saw_6, saw_7
    Which definitely explains why my totals do not add up when drilling down. Interestingly, if I run my second request without the prompt from Answers, the SQL request works like a charm:
    SET VARIABLE QUERY_SRC_CD='Report',SAW_SRC_PATH='/shared/01 - Financials/4. Pipeline/Pipeline - Current - T2',DISABLE_CACHE_HIT = 1;
    SELECT BUSINESS_UNIT.Segment saw_0, BUSINESS_UNIT."Business Unit" saw_1, OPPORTUNITY.CLOSEPROBABILITY saw_2, OPPORTUNITY.CLOSEPROBABILITY saw_3, YEAR(OPPORTUNITY.ESTIMATEDCLOSE) saw_4, OPPORTUNITY_ADDON.TCV_IN_USD/1000000 saw_5, OPPORTUNITY_ADDON.WEIGHTED_TCV_IN_USD/1000000 saw_6, CASE OPPORTUNITY.CLOSEPROBABILITY WHEN 100 THEN OPPORTUNITY_ADDON.TCV_IN_USD/1000000 ELSE 0 END saw_7 FROM "Sales"
    WHERE (OPPORTUNITY.STAGE NOT IN ('Lost', 'On Hold')) AND (YEAR(OPPORTUNITY.ESTIMATEDCLOSE) &gt;= YEAR(CURRENT_DATE)) AND
    ((({color:#ff0000}OPPORTUNITY.CLOSEPROBABILITY &gt; 25) AND (TIMESTAMPDIFF(SQL_TSI_MONTH, CURRENT_DATE,OPPORTUNITY.ESTIMATEDCLOSE) &lt;= 4)) OR ((OPPORTUNITY.CLOSEPROBABILITY &gt;= 10) AND (TIMESTAMPDIFF(SQL_TSI_MONTH, CURRENT_DATE,OPPORTUNITY.ESTIMATEDCLOSE) &gt; 4{color})))
    ORDER BY saw_0, saw_1, saw_2, saw_3, saw_4, saw_5, saw_6, saw_7
    Anybody had the same problem before?

    Here's the excerpt (it's relative to crashing, but I think it should also address the bug):
    # PRESENTATION SERVER CRASH AFTER UPGRADING TO 10.1.3.4 (Doc ID 756541.1)
    crash when they run the reports containing Pivot Table. This has been a known issue with version ... subsequently upgraded to version
    Doc Type:ALERTModified:2/10/2009

  • How to use an UNIX shell variable in sql where clause

    Hi ,
    In my shell script first I get the Date and time from the system into the shell variable.At the end of the shell script I need to run a sql script in which I want to use the variable value in the where clause . Is there any way we can use a shell variable value in SQl script ?. Any help is greatly appriciated .
    Thanks in advance,
    Sampath

    Try the following
    In Unix
    SQLPLUS <username>/<password> @MyScript.sql <UNIX_Variable>
    In SQL*Plus
    Reference the variable as &1
    select *
    from MyTable
    where MyDate = to_date('&1','<date_format>');

  • Using multiple values in a where clause, for values only known at runtime

    Dear all
    I am creating a PL/SQL program which returns multiple rows of data but only where it meets a set id values that a user has previously chosen. The id values are stored in an associative array and are chosen by a user in the preceding procedure at run time.
    I know all the table and column names in advance. The only things I don't know are the exact number of ids selected from the id column and what their values will be. This will only be known at runtime. When the procedure is run by the user it prints multiple rows of data to a web browser.
    I have been reading the following posting, which I understand to a large extent, Query for multiple value search But I cannot seem to figure out how I would apply it to my work as I am dealing with multiple rows and a cursor.
    The code as I have currently written it is wrong because I get an error not found message in my web browser. I think the var_user_chosen_map_list_ids in the for cursor loop could be the problem. I am using the variable_user_chosen_map_list_ids to store all the id values from my associatative array as a string. Which I modified from the code that vidyadhars posted in the other thread.
    Should I be creating a OPEN FOR ref cursor and if so where would I put my associative array into it? At the moment I take the value, turning it into a string and IN part in the WHERE clause holds the string, allowing the WHERE clause to read all the values from it. I would expect the where clause to read everything in the string as 1 complete string of VARCHAR2 data but this would not be the case if this part of the code at least was correct. The code is as follows:
    --Global variable section contains:
    var_user_chosen_map_list_ids VARCHAR2(32767);
    PROCEDURE PROCMAPSEARCH (par_user_chosen_map_list_ids PKG_ARR_MAPS.ARR_MAP_LIST)
    IS
    CURSOR cur_map_search (par_user_chosen_map_list_ids IN NUMBER)
    IS
    SELECT MI.map_date
           MT.map_title,
    FROM map_info MI,
         map_title MT,
    WHERE MI.map_title_id = MT.map_title_id
    AND MI.map_publication_id IN
    (var_user_chosen_map_list_ids);
    var_map_list_to_compare VARCHAR2(32767) := '';
    var_exe_imm_map VARCHAR2(32767);
    BEGIN
    FOR rec_user_chosen_map_list_ids IN 1 .. par_user_chosen_map_list_ids.count
    LOOP
       var_user_chosen_map_list_ids := var_user_chosen_map_list_ids ||
       '''' ||
       par_user_chosen_map_list_ids(rec_user_chosen_map_list_ids) ||
    END LOOP;
    var_user_chosen_map_list_ids := substr(var_user_chosen_map_list_ids,
                                            1,
                                            length(var_user_chosen_map_list_ids)-1);
    var_exe_imm_map := 'FOR rec_search_entered_details IN cur_map_search
    LOOP
    htp.print('Map date: ' || cur_map_search.map_date || ' Map title: ' || cur_map_search.map_title)
    END LOOP;';
    END PROCMAPSEARCH;EXECUTE IMMEDIATE var_exe_imm_map;
    I would be grateful of any comments or advice.
    Kind regards
    Tim

    I would like to thank everyone for their kind help.
    I have now successfully converted my code for use with dynamic SQL. Part of my problem was getting the concept confused a little, especially as I could get everything work in a static cursor, including variables, as long as they did not contain multiple values. I have learnt that dynamic sql runs the complete select statement at runtime. However even with this I was getting concepts confused. For example I was including variables and the terminator; inside my select string, where as these should be outside it. For example the following is wrong:
         TABLE (sys.dbms_debug_vc2coll(par_user_chosen_map_list_ids))....
    AND MI.map_publication_id = column_value;';Where as the following is correct:
         TABLE (sys.dbms_debug_vc2coll('||par_user_chosen_map_list_ids||'))....
    AND MI.map_publication_id = column_value';PL/SQL is inserting the values and then running the select statement, as opposed to running the select statement with the variables and then accessing the values stored in those variables. Once I resolved that it worked. My revised code is as follows:
    --Global variable section contains:
    var_user_chosen_map_list_ids VARCHAR2(32767);
    var_details VARCHAR(32767);
    PROCEDURE PROCMAPSEARCH (par_user_chosen_map_list_ids PKG_ARR_MAPS.ARR_MAP_LIST)
    IS
    BEGIN
    FOR rec_user_chosen_map_list_ids IN 1 .. par_user_chosen_map_list_ids.count
    LOOP
       var_user_chosen_map_list_ids := var_user_chosen_map_list_ids ||
       '''' ||
       par_user_chosen_map_list_ids(rec_user_chosen_map_list_ids) ||
    END LOOP;
    var_user_chosen_map_list_ids := substr(var_user_chosen_map_list_ids,
                                            1,
                                            length(var_user_chosen_map_list_ids)-1);
    var_details := FUNCMAPDATAFIND (var_user_chosen_map_list_ids);
    htp.print(var_details);
    END PROCMAPSEARCH;
    FUNCTION FUNCMAPDETAILS (par_user_chosen_map_list_ids IN VARCHAR2(32767)
    RETURN VARCHAR2
    AS
    TYPE cur_type_map_search IS REF CURSOR;
    cur_map_search cur_type_map_search;
    var_map_date NUMBER(4);
    var_map_title VARCHAR2(32767);
    begin:
    OPEN cur_map_search FOR
    'SELECT MI.map_date,
           MT.map_title
    FROM map_info MI,
         map_title MT,
         TABLE (sys.dbms_debug_vc2coll(' || par_user_chosen_map_list_ids || '))
    WHERE MI.map_title_id = MT.map_title_id
    AND MI.map_publication_id = column_value';
    LOOP
    FETCH cur_map_compare INTO
    var_map_date,
    var_map_title;
    var_details := var_details || 'Map date: '||
                        var_map_date ||
                        'Map title: ' ||
                        var_map_title;
    EXIT WHEN cur_map_compare%NOTFOUND;
    END LOOP;
    RETURN var_details;
    END FUNCMAPDETAILS;Kind regards
    Tim

  • Apex 4.0 Image Buttons to update SQL Where clause of Report?

    I made a table called Letters with 1 column in it called Letter and the data in it is simply A,B,C, to H. I made an apex form around this table and then created two image buttons A and B that display above the reporting area b/c i want to be able to click on the A image button and have it update the Where clause for the Letters table to be "Where Letter = A" (so once you click the A button, only the A will appear), same for the B button. I have attached a link to an album of images to show what i'm trying to do to better explain it. I just can't figure out what or how to make it so that the image button can update the where clause. I should note that i am relatively new to Apex and i tried using a dynamic action to do it but can't get this to work.
    Link to images of what i have so far-> http://imgur.com/a/guxkd/oracle_apex_40_use_image_buttons
    Any suggestions?
    Edited by: Brobot on Feb 8, 2011 9:58 PM

    Since you are using some kind of button(with images or otherwise) , add some attributes to identify them together aswell as uniquely.
    For instance if you add a name and an a common classname to each button
    For example, in button attributes for A this could be
    name="A" class="where_clause_button"You can use these attributes to trigger a Dynamic action which can refresh the report.
    Since you want the report to be filtered based on the button(ie using the "name" attribute of the corresponding button) , you need to set that value in some hidden item, say P100_FILTER_LETTER. and add a where clase to your Report Region' SQL Query
    WHERE <column name> = :P100_FILTER_LETTERNow create a Dynamic Action as
    Event :Click
    Triggering Element : jQuery selector
    Selector : *.where_clause_button*
    <li>True action 1 : Execute Javascript code
    filter_item_name = 'P100_FILTER_LETTER'
    this_button_name = $(this.triggeringElement).attr('name');
    //Set session state of Hidden Item before refresh
    var ajaxRequest=new htmldb_Get(null,$v('pFlowId'),'null',$v('pFlowStepId'));
    ajaxRequest.add( filter_item_name ,this_button_name );
    var ajaxResult=ajaxRequest.get();<li> True Action 2: Refresh
    Affected Element: Region
    Name : Choose Report Region Name
    Hope it helps

  • How to Get the required List Item values by using Where Clause

    I have two tables named "TAX_RULES","BILL"
    1. " Tax_Rules" (Sub_Head_Code,Tax_ID,Tax_Percentage)
    { While "Sub_Head_Code" field is unique,
    Tax_ID describes that there are two kinds of Tax_IDs based on Tax_percentage which is 6% for some Sub_Head_Codes and 3.5% for the remainng Sub_Head_Codes. I have given Tax_ID 1 for 6% and Tax_ID 2 for Sub_Head_codes having 3.5%. }
    2. "BILL" (Bill_ID,Sub_Head_Code,Tax_ID,Bill_Amount)
    {While "Bill_ID" describes unique Bill Identification Number,
    Sub_Head_Code and Tax_ID are behaving like composite foreign key from Tax_Rules table}
    I have design form for both tables.
    In BILL form i am trying to get values of Tax_ID from Tax_Rules table at run-time by using WHEN-NEW-FORM-INSTANCE.
    For this whenever i select a Sub_Head_Code in Bill Form, all the Tax_IDs that i have recorded against each Sub_Head_Code which is either 1 or 2 against 6% and 3.5% respectively.
    But I want that whenever i select a "Sub_Head_Code", Only that Tax_ID which is associated with that Sub_Head_Code ahould come in the LIST ITEM.
    I have used WHERE clause but that is useless.
    Following is the Code that i have applied in the WHE-NEW-ITEM-INSTANCE Trigger at FORM LEVEL
    <CODE>
    DECLARE
         rg_n1 VARCHAR2(40) :='TAX_ID';
         rg_idn1 RecordGroup;
         gc_idn1 GroupColumn;
         errcode NUMBER;
    BEGIN
         CLEAR_LIST('BILL.TAX_ID');
         rg_idn1 := Find_Group(rg_n1);
    IF      Id_Null(rg_idn1) then
              rg_idn1 := Create_Group(rg_n1);
         gc_idn1 := Add_Group_Column(rg_idn1,'EXPLAIN',CHAR_COLUMN,60);     
              gc_idn1 := Add_Group_Column(rg_idn1,'TAX_ID',CHAR_COLUMN,3);
         END IF;
         errcode := Populate_Group_With_Query(rg_idn1,'select TAX_ID,TAX_ID from TAX_RULES');
         POPULATE_LIST('BILL.TAX_ID',RG_IDn1);
    END;
    </CODE>

    In the Tax Rules table, you state:
    "Sub_Head_Code" field is unique
    In the Bill table, you state:
    Sub_Head_Code and Tax_ID are behaving like composite foreign key from Tax_Rules table
    If the Sub_Head_Code is unique, then it's acting as a primary key, so Sub_Head_Code and Tax_ID in the Bill table are not behaving like a composite foreign key. The Sub_Head_Code is a foreign key, and the Tax_ID is irrelevant as far as keys are concerned.
    It is not clear what it is you want to do.
    If you want to display the Tax_IDs from the Bill table when you select a Sub_Head_Code from the Tax_Rules table, then change your query to:
    select TAX_ID, TAX_ID from BILL where Sub_Head_Code = :Tax_Rules.Sub_Head_Code
    If you want to display the Tax_IDs from the Tax_Rules table when you select a Sub_Head_Code from the Bill table, then change your query to:
    select TAX_ID, TAX_ID from TAX_RULES where Sub_Head_Code = :Bill.Sub_Head_Code
    If this is not what you want, then clarify what it is you want to do. Don't say:
    "I want that whenever i select a "Sub_Head_Code", Only that Tax_ID which is associated with that Sub_Head_Code"
    because it is not clear what tables you are referring to.

  • Select multiple value in a where clause

    hello,
    im using developer 2000.
    suppose I have several values in a data grid. I want to use all of them in a where clause using IN operator or something. anybody knows how to do that. what I do is always insert all values in the grid into a temporary table and use that table in the where clause. is there any other easy, effective way of doing that?
    select *
    from table1
    where category in (-- I want to select multiple values form a data grid here--)
    thanks in advance.
    bonny.

    Hello Bonny,
    You might consider the use of PL/SQL Collection Types
    The first step in the process is to create a type and a table of that type.
    CREATE OR REPLACE TYPE DateType IS OBJECT ( Arg1 DATE );
    CREATE OR REPLACE TYPE TableList IS TABLE OF DateType;
    DECLARE
    list1 tablelist;
    BEGIN
    SELECT datetype (arg1)
    BULK COLLECT INTO list1
    FROM table1;
    FOR c1 IN (SELECT arg1
    FROM TABLE (CAST (list1 AS tablelist)))
    LOOP
    ---- Your code -----;
    END LOOP;
    END;
    For further insight please refer: http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/05_colls.htm
    Regards.

  • PL/SQL: how to use in parameter in select sql where clause

    Hi
    in a procedure, I need to apply 'in parameter' in 'where clause' along with other table fields. Purpose is to create dynamic select querry with multiple conditions.
    select count(*) from table xx
    where y_code=2008 and v_type in ('SI', 'TI', 'DI') ;
    my requirement is replace 'and v_type in ('SI', 'TI', 'DI')' with in parameter. pls note in paramter may contain null value.
    Regards

    ... e.g. why on earth do you want to pass in a string to be appended to the WHERE clause of an SQL.I second that and I strongly advice NOT to do it. If you really want to do it, then come back and show us, how you would prevent SQL injection. This approach is too dangerous (and too complex) IMHO.
    Do it straight forward as in the article of Tom Kyte (link in the post of BluShadow above)

  • SQL WHERE clause

    I want to use dynamic where clause in select statement. For example in a query like
    SELECT * FROM emp &where_clause_options
    I am constructing my where_clause_option within a IF-ELSE-ENDIF construct which is soemthing like this.
    if x=10 then
    where_clause_option := 'where dept = 10 and job = 'CLERK'
    else
    where_clause_option := 'where sal >3000'
    end if;
    Now how to specify it in the select statement?
    By the way DECODE statement does not work in WHERE clause.

    Thanks for your suggestion. I know that decode does not work that way in where clause although it may be used for establishing list of columns in the SELECT startement. And that is exactly what has raised this issue that then how to get the dynamical where clauses from within the code. By the way my code is plsql based and I am running it in sqlplus environment.
    I have tried to use the lexical parameter along with a combinition of DEFINE but define is uncontrolable in a conditional construct and hence the DEFINE in the last part of the IF then elsif else construct overrides previous defines and thus always passes to &my_where_clause1 the value defined in the last DEFINE statement. Here is how I tried to use Define:
    DECLARE --main
    v_sex varchar2(5);
    my_where_clause1 varchar2(50);
    Function myfunction return boolean is
    begin
    some code..........
    if v_sex = 'MALE' then
    DEFINE my_where_clause1 = 'and AGE > 60';
    else
    DEFINE my_where_clause1 = 'and AGE between 45 and 55';
    end if;
    some code......
    end -- Function myfunction;
    CURSOR mycursor is select patient_id from patient_history where Symptom = 'RESPIRATORY' &my_where_clause1;
    BEGIN -- main
    some code.....
    if myfunction = TRUE then
    for v_mycursor in mycursor Loop
    some code.....
    end loop;
    end if;
    END -- main;
    Although this provides me with lexical parameter functionality within my PLSQL code but I am unable to control the DEFINE. Neither DEFINE-lexicial combinition nor the DECODE are helping in this scenario.
    I am sure that there would be some way to implement it. So my call for help is still on.

  • [SQL] Where clause problem with subqueries

    Hi,
    I'm writing a query for an apex application where i have a field (P47_UNNR) for filtering. In my where clause I try to do this:
    ... AND qo.pk_id IN
    CASE
    WHEN :P47_UNNR IS NULL
    THEN
    (SELECT pk_id FROM quote_orders)
    ELSE
    (SELECT QOR.FK_QUOTE_ORDER_ID
    FROM QUOTE_ORDER_RIDS QOR
    JOIN
    RIDS RID
    ON RID.PK_ID = QOR.FK_RID_ID
    WHERE RID.NAME LIKE :P47_UNNR)
    END
    But it gives an error "ORA-01427: single-row subquery returns more than one row"
    I have tried multiple ways to get around this problem but don't seem to be able to do this. Does anyone have a suggestion on how to solve this?

    Hi Niels,
    First try with separating the query.
    First try with:
    CASE
    WHEN :P47_UNNR IS NULL
    THEN
    (SELECT pk_id FROM quote_orders)
    END;check SELECT pk_id FROM quote_orders this query returning only one values or not???
    Then try with
    CASE
    WHEN :P47_UNNR IS NULL
    THEN
    (SELECT pk_id FROM quote_orders)
    ELSE
    (SELECT QOR.FK_QUOTE_ORDER_ID
    FROM QUOTE_ORDER_RIDS QOR
    JOIN
    RIDS RID
    ON RID.PK_ID = QOR.FK_RID_ID
    WHERE RID.NAME LIKE :P47_UNNR)
    ENDCheck this
    SELECT QOR.FK_QUOTE_ORDER_ID
    FROM QUOTE_ORDER_RIDS QOR
    JOIN
    RIDS RID
    ON RID.PK_ID = QOR.FK_RID_ID
    WHERE RID.NAME LIKE :P47_UNNRquery returning one values or not??
    If those returns more than one value , the check whether there is any duplication value's present, remove that duplicate value from your table.
    if you cant remove just add rownum =1 condition in your where clause.
    Cheers,
    San

  • Trying to use parameter variable as column identifier in SQL where clause

    Hey guys,
    Doing a college project... would really appreciate some help. I am trying to use a variable in the where clause of a select cursor in PL/SQL. The code is this:
    procedure results(p_search_entry varchar2, p_search_field varchar2) is
    cursor c_results is
    select * from physics_b where p_search_field = p_search_entry;
    begin
    for cv_results in c_results
    loop
    -- loop through actions
    end loop;
    The problem is that I don't know how to get the where clause to accept the variable passed into the procedure as the field name. Does anyone know the syntax for this?
    Thanks very much!

    To suit your requirement use ref cursor..
    If your database is 9i and upwards you can use sys_refcursor as I have used or else you can declare the cursor shown in the statement below
    type c_result is ref cursor;
    c_results c_result;
    Jus replace these two statement in the example if your oracle database is prior to 9i
    Eg:
    procedure results(p_search_entry varchar2, p_search_field varchar2) is
    qry_stmt VARCHAR2(1000) ;
    c_results sys_refcursor;
    begin
    qry_stmt := 'select * from physics_b where '||p_search_field|| '='|| p_search_entry
    open c_results for qry_stmt
    loop
    <fetch as like normal cursor>
    <ur normal cursor operation etc....>
    end loop;
    end results;
    Sorry I posted twice
    Message was edited by:
    Shasi

  • SQL Where clause when comparing dates and times in ASP

    Hello,
    I am trying to pull data from my database which is dependant on both the date and time in HH24 format. So, my where clause looks something like this:
    select * from thisTable where activity_time >= myCurrentDate
    (myCurrentDate is a variable that is built which gives it the following format DD-MON-YYYY HH24:MI:SS)
    So, the actual passed string to my call is:
    select * from thisTable where ACTIVITY_TIME >= '02-DEC-2008 18:22:00' order by ACTIVITY_TIME asc
    However, when calling this, I get the famous "ORA-01830: date format picture ends before converting entire input string"
    Can anyone please help me?!?!?!?
    Thanks in advance

    Enrique answered your immediate question, but I'd like to point up a broader issue, and that is that you should <b><u>always</u></b> use the TO_DATE and TO_CHAR functions at the sql statement level when working with date datatypes. That way you are never dependent on some default over which you have no control. I call that is 'defensive coding'.

  • Using a report value for a where clause in other report

    Hi All,
    i'm getting kinda nuts here. I created a page with three reports.
    First report show the name of the user who logged in with his/her whole name. Second report shows the year, week, begin/end date of the week for the user in the first report. The third report show the hours the user worked in the week selected in the second report.
    The link between first and second report is on column report. Somehow i managed it to work with second_report.mdw_code = :P3_ACRONIEM. I have no idea were this P3_ACRONIEM item is coming from, while i have no items in my page whatsoever. Now i need to link the second report to the third report. I have to use the second_report.mdw_code, second_report.year and second_report.week but i have no idea how to link these together. Any idea's? (Like making items, but then i have no idea how to link that item to the value in the second report). Please help.
    Kind regards,
    Dave
    The link between the first and the second i could get it to work with :P3_ACRONIEM. I have no idea where this ITEM is coming from, because i have no items in my page (and it's the only page in the application). Then

    Hi Dave,
    If I understand you correctly, you have a one report that lists users, a second report that lists dates and a final report that shows hours worked?
    If so, you may find it easiest to have hidden fields on your page and base the second and third reports on these using appropriate WHERE clauses. (I generally put hidden fields in a region in the "After Header" position)
    So, if the first report contains a USER_ID field, have a hidden field called P1_USER_ID. The link on the first report will branch back to the same page and set the value of P1_USER_ID to #USER_ID# The second report can then use WHERE USER_ID = :P1_USER_ID. When the page reloads, the second report redisplays and is filtered to show only those records relating to the selected USER_ID in the first report.
    To extend this, if the second report contains WEEK_NUMBER, it should have a link that branches back to the same page and sets a hidden P1_WEEK_NUMBER field with #WEEK_NUMBER#. The third report should when have WHERE WEEK_NUMBER = :P1_WEEK_NUMBER AND USER_ID = :P1_USER_ID. You can, if need be, have and set more than one hidden field during each link.
    Regards
    Andy

  • Use of DECODE and NULL value in a WHERE clause

    hi all,
    I came into an issue trying to use the DECODE function in a simple where clause.
    this is my test case
    CREATE TABLE tab_test (lev NUMBER, code VARCHAR2(10), val VARCHAR2(10));
    INSERT INTO tab_test VALUES (1, NULL, 'val11');
    INSERT INTO tab_test VALUES (1, NULL, 'val12');
    INSERT INTO tab_test VALUES (1, '13', 'val13');
    INSERT INTO tab_test VALUES (2, '21', 'val21');
    INSERT INTO tab_test VALUES (1, '22', 'val22');
    INSERT INTO tab_test VALUES (1, '23', 'val23');
    and this is the query
    SELECT * FROM tab_test WHERE code = DECODE(:lev,1,NULL,:cod)
    as you can see running this query, setting :lev to 1 will return an empty record set, instead of the expected first two rows (as it will be, running "select * from tab_test where code is null").
    is there a way to overcome this issue? thanks for help

    hi Frank,
    I can confirm that the queries do work when run on TOAD, but do not when they are put in the WHERE clause of my data block. I guess the problem relies on some data block setting; I should investigate on Forms forum.
    Anyway, here is my test case, including data and some examples. You can realize that it works good
    CREATE TABLE TAB_TEST
    LEV NUMBER,
    CODE VARCHAR2(10 BYTE),
    VAL VARCHAR2(10 BYTE)
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (3, 'val21', 'val3_211');
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (2, 'val21', 'val3_212');
    Insert into tab_test
    (LEV, VAL)
    Values
    (1, 'val11');
    Insert into tab_test
    (LEV, VAL)
    Values
    (1, 'val12');
    Insert into tab_test
    (LEV, VAL)
    Values
    (1, 'val13');
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (2, 'val11', 'val21');
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (2, 'val12', 'val22');
    Insert into tab_test
    (LEV, CODE, VAL)
    Values
    (2, 'val13', 'val23');
    COMMIT;
    SELECT * FROM TAB_TEST
    CONNECT
    BY PRIOR val = code
    START WITH (CASE
    WHEN :LIV = 1 AND code IS NULL THEN 'OK'
    WHEN :LIV != 1 AND code = :COD THEN 'OK'
    END = 'OK')
                   AND VAL = :V
    :LIV = 1
    :COD = [any]
    :V = 'val11'
    LEV     CODE     VAL
    1          val11
    2     val11     val21
    3     val21     val3_211
    3     val21     val3_212
    :LIV = 1
    :COD = [any]
    :V = 'val12'
    LEV     CODE     VAL
    1          val12
    2     val12     val22
    :LIV = 2
    :COD = 'val11'
    :V = 'val21'
    LEV     CODE     VAL
    2     val11     val21
    3     val21     val3_211
    2     val21     val3_212

  • [Solved] Named Bind Variables at Runtime - SQL WHERE clause issue

    Hey 'all,
    I've been having this issue today with a Search page using Named Bind Variables at Runtime for the search parameters for the WHERE clause in the view objects SQL.
    I've got everything working except for a clearing method which I've created so that the user can clear the current WHERE clause from the SQL statment and set it as 1=2 (so that it doesn't do a blind query on load).
    The method can clear and set the WHERE clause to 1=2 only when there is already one there.
    Below are the methods: (located in my view object class)
    public void findInvoiceById(Number invoiceId){
        setWhereClause("invoice_id = :P_INVOICE_ID");
        defineNamedWhereClauseParam("P_INVOICE_ID",null,null);
        setNamedWhereClauseParam("P_INVOICE_ID",invoiceId);
        executeQuery();
    public void clearCriteria(){
        setWhereClause("1=2");
        removeNamedWhereClauseParam("P_INVOICE_ID");
        executeQuery();
    }The error which I get is the following - this happens when the button is pressed twice in a row, or when no query has been passed previously.
    1. JBO-29000: Unexpected exception caught: oracle.jbo.NoDefException, msg=JBO-25058: Definition P_INVOICE_ID of type Variable not found in SupplierInvoicesView1
    2. JBO-25058: Definition P_INVOICE_ID of type Variable not found in SupplierInvoicesView1
    Any help with this would be greatly appreciated!
    Cheers,

    Hi Bonnie,
    we have it working ok, but still feel that there is room for improvement in the design.
    For us the key factors are:
    Pages based on the same view object that can be queried multiple ways.
    We don't want to put design time bind variables in because it limits the use of the VO
    We don't wan't multiple VO's with different where clauses.
    The page is displaying the same table columns and fields, but the where clause must be dynamic.
    We only want to query on the search field entered (some of our tables are massive)
    TopLink named queries are really what we are after, but we don't want to forgo all the other ADF BC functionality. The only examples of ViewCriteria in the developer guide had literals in the where clause and no bind variables. The View Criteria may still be an option, but it appeared quite complex compaired to directly adding and removing bind variables at runtime.
    a couple of footnotes:
    the following methods are used to clear the runtime variables prior to reusing the VO (thanks to John Stegman for the pointer on the exception handler):
        public void clearBindVariable(String bindVariableName){
            try
                removeNamedWhereClauseParam(bindVariableName);
            catch (NoDefException e)
        public void clearBindVariables(){
            clearBindVariable("P_INVOICE_ID");
            clearBindVariable("P_INVOICE_NUM");
            clearBindVariable("P_SUPPLIER_NAME");
            clearBindVariable("P_INVOICE_DATE_FROM");
            clearBindVariable("P_INVOICE_DATE_TO");
            clearBindVariable("P_SUPPLIER_NUMBER");
        }We are using 1=1 and 1=2 in the where clause to supress blind querying. 1=2 is applied when ever we are not explicitely searching for something. We had a problem with using the refresh condition ${adfFacesContext.postback == true} which I posted about here:
    executeQuery called twice using ${adfFacesContext.postback == true}
    Would still gladly hear other ideas on a better reuse design.
    regards,
    Brenden

Maybe you are looking for