Using 'NOT IN' Within a SQL Statement

Does anyone know why the following SQL statement does not return any values? The problem is with the SELECT statement within the 'NOT IN' clause. When explicitly typing in the part_ids returned from the select statement, everything works as expected.
Thanks for any help.
SELECT Distinct Part_Id, Trans_Date
     FROM Invctrl
     WHERE Trans_Type = 0
     AND Trans_Date BETWEEN To_Date( '1-Mar-2006 00:00:00', 'dd-mon-yyyy hh24:mi:ss' )
     AND To_Date( '31-Jan-2007 23:59:59', 'dd-mon-yyyy hh24:mi:ss' )               
     AND Part_Id NOT IN (SELECT part_Id From InvCtrl WHERE Trans_Date < To_Date( '1-Mar-2006 00:00:00', 'dd-mon-yyyy hh24:mi:ss'))

'NOT IN' should be avoided where ever we can.
Change your query to 'IN' clause as below and it should work.
SELECT DISTINCT part_id, trans_date
           FROM invctrl
          WHERE trans_type = 0
            AND trans_date BETWEEN TO_DATE ('1-Mar-2006 00:00:00',
                                            'dd-mon-yyyy hh24:mi:ss'
                               AND TO_DATE ('31-Jan-2007 23:59:59',
                                            'dd-mon-yyyy hh24:mi:ss'
            AND part_id IN (
                   SELECT part_id
                     FROM invctrl
                    WHERE trans_date BETWEEN TO_DATE ('1-Mar-2006 00:00:00',
                                                      'dd-mon-yyyy hh24:mi:ss'
                                         AND TO_DATE ('31-Jan-2007 23:59:59',
                                                      'dd-mon-yyyy hh24:mi:ss'
                   MINUS
                   SELECT part_id
                     FROM invctrl
                    WHERE trans_date <
                             TO_DATE ('1-Mar-2006 00:00:00',
                                      'dd-mon-yyyy hh24:mi:ss'
[pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • How do I use a variable within a sql statement

    I am trying to use a local variable within an open SQL step but I keep getting an error.
    My sql command looks like this "SELECT BoardDetailID FROM BoardDetails WHERE SerialNumber = " +  locals.CurrentSerialNo
    If I replace the locals.CurrentSerialNo with an actual value such as below the statement works fine.
    "SELECT BoardDetailID FROM BoardDetails WHERE SerialNumber = " +  " 'ABC001' " 
    Can someone tell me how to correctly format the statement to use a variable?

    Hi,
    Thanks for the reply. I have changed the required variable to a string, but with no success. I have reattached my updated sequence file and an image of the error.
    When looking at the Data operation step I see that the sql statement is missing everything after the last quotation mark.
    Thanks again,
    Stuart
    Attachments:
    Database Test Sequence.seq ‏10 KB
    TestStand error.JPG ‏37 KB

  • SSIS The parameterized sql statement yields metadata which does not match the main SQL statement

    Hi all,
    I'm getting the above error when trying to execute a custom lookup.  What I'm trying to do is lookup the minimum promotional price between date ranges.  The SQL executes fine in SSMS
    SELECT refTable.PRICE
    FROM ( SELECT MIN(PRICE) AS PRICE ,
    NAME ,
    ITEMRELATION ,
    FROMDATE ,
    TODATE
    FROM [dbo].[AllCustPrices]
    GROUP BY NAME ,
    ITEMRELATION ,
    FROMDATE ,
    TODATE
    ) [refTable]
    WHERE [refTable].[NAME] = ?
    AND [refTable].[ITEMRELATION] = ?
    AND ? BETWEEN [refTable].[FROMDATE]
    AND [refTable].[TODATE]
    but errors in SSIS?

    Apologies, totally forgot i posted a question on here.  I still haven't resolved this.  full error text is TITLE: Package Validation Error
    Package Validation Error
    ADDITIONAL INFORMATION:
    Error at Data Flow Task [Lookup MIN Price [440]]: The parameterized SQL statement yields metadata which does not match the main SQL statement.
    Error at Data Flow Task [SSIS.Pipeline]: "Lookup MIN Price" failed validation and returned validation status "VS_ISBROKEN".
    Error at Data Flow Task [SSIS.Pipeline]: One or more component failed validation.
    Error at Data Flow Task: There were errors during task validation.
     (Microsoft.DataTransformationServices.VsIntegration)
    BUTTONS:
    OK
    If I take off the MIN function and just put * SSIS is quite happy, it does not like MIN for some reason?
    I'm really stumped with this... checked metadata for third parameter which is W/C Date DT_DBTIMESTAMP which is same as FROMDATE, TODATE where i'm using BETWEEN...

  • How to use presentaion variable in the SQL statement

    Is there any special syntax to use a presentation variable in the SQL Statement?
    I am setting a presentation variable (Fscl_Qtr_Var)in the dashboard prompt.
    If i set the filter as ADD->VARIABLE->PRESENTATION, it shows the statement as 'Contract Request Fiscal Quarter is equal to / is in @{Fscl_Qtr_Var} '.
    And this works fine but when i convert this to SQL, it returns
    "Contract Request Date"."Contract Request Fiscal Quarter" = 'Fscl_Qtr_Var'
    And this does not work.It is not being set to the value in the prompt.
    I need to combine this condition with other conditions in the SQL Statement. Any help is appreciated. Thanks

    Try this: '@{Fscl_Qtr_Var}'

  • IScript problem - Cannot use an input in a sql statement

    I get the input from an input box and it is correct
    &param = %Request.GetParameter("Dept");
    I try to use it in a sql statement lke this and nothing displays even though it its entered correctly and the value exists in the table
    Local SQL &usersCursor = CreateSQL("SELECT EMPLID, BIRTHDATE, NAME FROM PS_EMPLOYEES WHERE DEPTNAME_ABBRV = '&param'");
    If I leave out the single quotes around and do it like this &param then it errors out
    Local SQL &usersCursor = CreateSQL("SELECT EMPLID, BIRTHDATE, NAME FROM PS_EMPLOYEES WHERE DEPTNAME_ABBRV = &param");
    I need help structuring this correctly
    Thanks,
    Allen Cunningham

    Hi,
    CreateSQL does not execute the sql statement, it just creates an SQL object, which you have to execute.
    Something like this:
    &param = %Request.GetParameter("Dept");
    Local SQL &usersCursor = CreateSQL("SELECT EMPLID, BIRTHDATE, NAME FROM PS_EMPLOYEES WHERE DEPTNAME_ABBRV = :1", &param);
    While usersCursor.Fetch(&Emplid, &Birthdate, &Name)
    /* do processing*/
    End-While;

  • Using Toplink to generate UPDATE sql statements?

    I have a need to generate a UPDATE sql statement.
    This statement will run at startup and will not effect the cache, as no objects will be loaded prior to this command running.
    I realize that I can execute arbitrary SQL using Session, however, I have the additional requirement that this UPDATE is compatible with the DB it is running on.
    So, I want to use TopLink to generate an UPDATE statment perhaps using the query framework. Is this possible? Is there any way to use TopLink's ability to create SQL before passing this into a Session for execution?

    In the current versions your only option is to provide the UPDATE SQL directly using the executeCall(new SQLCall("UPDATE ...")).
    In 10.1.3 there exists an UpdateAllQuery intended to do such batch update calls. It will additionally invalidate any cached objects if they were to exist.
    Doug

  • Using OS Commands within PL/SQL

    How can I use Operating system commands from within PL/SQL procedures or functions? Kindly explain with an example.
    Thanx,
    SB

    Previously we have used external procedures to use Windows kernel32.dll to start an external program. However this does not work on Oracle9i.
    Instead I have modified an example in Java to acceive this. The following class can start an external program either synchronously or asynchronously and in synchronous mode it will return the programs output.
    import java.io.*;
    import java.util.*;
    public class util
    // Executes an operating system command. The command shall be fully qualified.
    // The Java connects with silent login. No environment set-up files are run
    // and no path is set. The mode can be "sync" or "async" for respectively
    // synchronous and asynchronous execution
    static public int OSCmd(String cmd, String mode, String[] output)
    throws IOException, InterruptedException
    System.out.println("OSCmd "+cmd+" ("+mode+")");
    output[0]="";
    // start command
    Process proc = Runtime.getRuntime().exec(cmd);
    if (mode.equals("sync"))
    // get command's stdout and stderr
    InputStream stdout = proc.getInputStream();
    InputStream stderr = proc.getErrorStream();
    String str;
    // Stdout
    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
    while ((str = br.readLine()) != null)
    output[0]+=str+"\n";
    br.close();
    // Stderr
    br = new BufferedReader(new InputStreamReader(stderr));
    while ((str = br.readLine()) != null)
    output[0]+=str+"\n";
    br.close();
    // wait for command to terminate
    proc.waitFor();
    return proc.exitValue();
    return 0;
    You need the following permissions:
    call dbms_java.grant_permission('COMMON', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'execute');
    call dbms_java.grant_permission('COMMON', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
    call dbms_java.grant_permission('COMMON', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
    And then create the Java stored procedure:
    create or replace function os_cmd2(p_cmd varchar2, p_mode varchar2, p_output in out varchar2) return number
    as language java
    name 'util.OSCmd(java.lang.String, java.lang.String, java.lang.String[]) return int';

  • Can i use commit in between pl sql statements

    Hi,
    I have written program unit , in that I used insert statements and after that I used commit command.
    But in runtime it's getting oracle error unable to insert . because I used some non database items and database items
    so that it's coming error.
    But my question is , Can i use commit after executing some statements in program unit procedure.
    Thanks in advance.

    FORMS_DDL restrictions
    The statement you pass to FORMS_DDL may not contain bind variable references in the string, but the
    values of bind variables can be concatenated into the string before passing the result to FORMS_DDL.
    For example, this statement is not valid:
    Forms_DDL ('Begin Update_Employee (:emp.empno); End;');
    However, this statement is valid, and would have the desired effect:
    Forms_DDL ('Begin Update_Employee ('||TO_CHAR(:emp.empno)
    ||');End;');
    However, you could also call a stored procedure directly, using Oracle8's shared SQL area over
    multiple executions with different values for emp.empno:
    Update_Employee (:emp.empno);
    SQL statements and PL/SQL blocks executed using FORMS_DDL cannot return results to Form
    Builder directly.
    In addition, some DDL operations cannot be performed using FORMS_DDL, such as dropping a table
    or database link, if Form Builder is holding a cursor open against the object being operated upon.
    Sarah

  • Limitations in using a function within a select statement

    I have a function which retrieves various data elements from the
    database and formats it accordingly. The data (varchar2)
    returned could be in excess of 2,000 characters length.
    I need to use the returned data as part of a view. I am able to
    use the function in a "select" statement, but when I use it with
    returned data in excess of 2,000 chars, I get the following
    error:
    ORA-06502: PL/SQL: numeric or value error
    This error is occurring whenever the returned data is in excess
    of 2,000 characters.
    Is there an alternative method to what I am proposing, I have
    tried alternative data types but if I am able to use it in a
    "select" statement, I get the above error when the returned
    length exceeds 2,000 chars.
    Thanks
    Peter

    are u using oracle 7. varchar2 limit in 8 is 4000.

  • Using a var within an Include statement

    What syntax do I use in order to put a variable within an Include statement...
    <%@ include file="<%= varhere %>.htm" %>
    Thanks for any help!

    use
    <include>
    <param name=" something " value="34"/>
    </include>

  • How to write named query if we want to use IN syntax in our sql statement?

    I cannot find a suitable category about named query, so please move to appropriate place if there is any.
    When we write named query, below statement is fine.
    Query q2 = em.createQuery("SELECT o FROM Table1 as o WHERE field1 = :input1");             q2.setParameter("input1", "value1");
    Now, my question is, how can I write this type of query when we want to use the IN sql syntax? As below statement CANNOT return correct results. Even I tried to put a pair of single quote [ ':input2' ], it won't help also.
    Query q2 = em.createQuery("SELECT o FROM Table1 as o WHERE field2 IN (:input2)");             q2.setParameter("input1", "3633, 3644");
    Can anyone suggest? Thanks.

    roamer wrote:
    Now, my question is, how can I write this type of query when we want to use the IN sql syntax? As below statement CANNOT return correct results. Even I tried to put a pair of single quote [ ':input2' ], it won't help also.
    Query q2 = em.createQuery("SELECT o FROM Table1 as o WHERE field2 IN (:input2)");
    q2.setParameter("input1", "3633, 3644");
    Can anyone suggest?The above is in your code right? Not in some configuration file?
    Then you do it the same way as with regular jdbc/sql.
    1. You start with a collection of values - call it collection A.
    1. Create a for loop that dynamically creates the string using 'bind' variables (whatever you want to call the 'colon' entity in the above).
    2. Call the createQuery method using the string that was created
    3. Create a second loop that iterates over A and populates with setParameter.
    Pseudo code
            Object[] A = ...
            String sql = "SELECT o FROM Table1 as o WHERE field2 IN (";
            for (int i=1; i <= A.length; i++)
                  if (i == 1)
                     sql += ":input" + i;
                 else
                     sql += ",:input" + i;
            sql += ")";
            Query q2 = em.createQuery(sql);
            for (int i=1; i <= A.length; i++
                  q2.setParameter("input" + i, A[i-1]);
                  }By the way there is a jdbc forum.

  • How to query using CGI path for 'IN' sql statement

    Some problems that requires help:
    I have a report that requires a query which has 'IN' statement in SQL query. For example: SELECT EMP_ADDRESS1 FROM EMPLOYEE WHERE EMP_NO IN (:EMP_NO).
    I am going to query the result of this query using CGI. My peoblem starts here - I can't be passing a list of parameter for ':EMP_NO' because the path does not accept escape characters. I can't be put a query path below:
    <HTML>http://172.188.2.7/dev60cgi/rwcgi60.exe?server=9iAS&mode=default&destype=localfile&desformat=\\pri_wnt\generic&report=gcgd1.rdf&userid=comm/comm@employee<B>&emp_no='A','B','C'<B></HTML>
    What I am doing is that I will have a front end written in JAVA and display a listing of Employee available in the company. The user will be able to choose whatever employee on the front end. Then, I will call the CGI path to display the result to the user.
    Pls help. Kindly email personally([email protected]) or reply here.
    Thank you

    You'll need to escape your single quotes using %XX where XX is the hex code corresponding to the special character you want to use. I'm not sure what the escape code is for quotes. I know that if you wanted to have a space, this:
    ....../rwcgi60.exe?key+P_city='San Francisco'+....
    would need to look like:
    .../rwcgi60.exe?key+p_city=San%20Francisco+...
    You'll need to find out what the number for quote is. HOpe that helps a bit.
    Toby

  • Date KF is not avaialbe in the SQL statement

    Hi,
              We  have the date as a KF in the query, but it is not populating any date.So we like to check the SQL code in the RSRT for analysis,
                    We found that in the select area of the SQL code date field is not avaialbe , how to confirm this that field is not seelcted inthe sql statment.

    Hi,
    For queries such as Update, Create table or Drop table, you should only have "Open Statement" step to do the operations.
    If you use "Select" statement in the "Open Statement" step, then you would need a "Data Operation" step to operate on the recordset returned by the "Select" statement.
    If your use case is to only update a value of an existing row/entry using an "Update" query, then the "Open Statement" step would just work as it is without a "Data Operation" step.
    You can refer to TestStand Help for more details
    TestStand 2014: <Examples>\Built-In Step Types\Database Step Types\Database Step Types.seq
    TestStand 2013 or earlier: <Examples>\Database\WritingAndReadingTableData.seq
    Hope this helps.
    Regards,
    Sahana

  • Using accept command within PL/SQL block

    Hi all i have a following Pl/SQL block which ia =as follows :-
    declare
    begin
    ...certain statements using while
    end;
    i need to take the user input using accept
    if i put the accept stmt betweeen begin and end i am getting following error :-
    accept myv number default 10 prompt 'Enter a number: '
    ERROR at line 48:
    ORA-06550: line 48, column 8:
    PLS-00103: Encountered the symbol "MYV" when expecting one of the following:
    := . ( @ % ;
    ORA-06550: line 48, column 30:
    PLS-00103: Encountered the symbol "PROMPT" when expecting one of the following:
    * & = - + ; < / > at in is mod remainder not rem
    <an exponent (**)> <> or != or ~= >= <= <> and or like
    between || multiset member SUBMULTISET_
    Let me know how can i include accept stmt in Pl/SQL block
    Thanks

    You're missing a fundamental concept here.
    PL/SQL = embedded 4GL programming language in the Oracle database.
    SQL*Plus = CLI (Command Line Interface) client for an Oracle database.
    The ACCEPT command is a SQL*Plus command. Not a PL/SQL command.
    The PL/SQL engine sits inside the Oracle Server Process that services your client (SQL*Plus) session. That server process does not know who/what/where you are as a physical client. It does not know what platform and o/s you are using. It does not know what client you are using. It is after all a server process and should not and need not to know that.
    Nor can that Oracle Server Process running on the Data Server Platform access you client's hard drive, keyboard, mouse, screen, printer and so on.
    PL/SQL running in this Oracle Server Process therefore cannot read your keyboard to accept end-user input. PL/SQL therefore cannot write data to your screen.
    You need to make a clear distinction between SQL*Plus (a client) and Oracle PL/SQL (the server).

  • How do I use bind variables for the SQL statements having IN clause

    SELECT id, name FROM t
    WHERE id in (10,20,30)
    As the IN list will have 'n' number of values, I am not able to specify fixed number of bind
    variables like
    SELECT id, name FROM t
    WHERE id in (?,?,?....)

    452051 wrote:
    I am not able to specify fixed number of bind variablesYou could use collection:
    SQL> create or replace force
      2    type NumList
      3      as
      4        table of number
      5  /
    SQL> select ename from emp where deptno member of NumList(10)
      2  /
    ENAME
    CLARK
    KING
    MILLER
    SQL> select ename from emp where deptno member of NumList(10,20,30)
      2  /
    ENAME
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    ENAME
    JAMES
    FORD
    MILLER
    14 rows selected.
    SQL> This way you have one bind variable - collection.
    SY.

Maybe you are looking for