Duplicate records returned by db adapter

Hi,
We have a DB Adapter design as following.
From a J2EE application, an invoking procedure at the adapter is triggered. This invokes the DB adapter which inturn invokes the implemetned procedure which
returns a VARRAY.
J2EE application is deployed on the AS 10g Protal side.
The implemented procedure further invokes a legacy procedure which returns a Refcursor.Inside this implemetned procedure, the cursor is fetched into a
Recortype and each element of the record type is added to an Object (of type MPLUS_MPLUS_BankGurDet_OAI_V1). Then each of this object is added to a VARRAY and this VARRAY is returned to the invoking procedure.
The problem we face is that, in the returned the varray, there is always a duplicate of the last recored. That is if we have , say 5 records, then when we manipulate the VARRAY, there will 6 recored and the sixth record will be a duplicate of the 5th one.
Why is this happening. I have attached the code I used and log file. This is happening for all cases where VARRAY is returned. I have attached only one set
here.The log file attached clearly show the duplicate records.
-- All these is defined at the Legacy system
-- Following is a object definition used by the implemented procedure to return a collection of objects.
TYPE MPLUS_MPLUS_BankGurDet_OAI_V1 IS OBJECT (
AG_CODE VARCHAR2(1000),
AMT_NO NUMBER,
BANK VARCHAR2(1000),
VAL_FROM DATE,
VAL_TO DATE,
GUAR_NO VARCHAR2(1000)
-- Following is the defintion of Varray returned by the implemented procedure.
TYPE MPLUS_MPLUS_BankGurDet_OAI_Arr IS VARRAY(1000) OF MPLUS_MPLUS_BankGurDet_OAI_V1;
-- This is the implemented procedure called by adapter. This returns a Varray of the above object.(MPLUS_MPLUS_BankGurDet_OAI_V1).
PACKAGE Mplus AS
TYPE MY_TYPE IS REF CURSOR;
PROCEDURE imp_bankGurDet_OAI_V1(
i_CUSTOMER_CODE IN LONG,
i_CURRENT_DATE IN DATE,
o_RESULT OUT MPLUS_MPLUS_BankGurDet_OAI_Arr
END Mplus ;
PACKAGE BODY Mplus AS
PROCEDURE imp_bankGurDet_OAI_V1(
i_CUSTOMER_CODE IN LONG,
i_CURRENT_DATE IN DATE,
o_RESULT OUT MPLUS_MPLUS_BankGurDet_OAI_Arr
AS
Type BANK IS RECORD(agencyname VARCHAR2(1000),Amout NUMBER,BankName VARCHAR2(1000),validfrom date , validto date,guarenteeno varchar2(1000));
RECS MY_TYPE; -- Ref cursor
BANKDETAILS_REC BANK ;
BANKDETAILS_OBJ MPLUS_MPLUS_BANKGURDET_OAI_V1;
i Number;
dummy number;
BEGIN
WF_MP_ADVT.SP_ADV_AGE_BANK_GRTY(i_CUSTOMER_CODE,i_CURRENT_DATE,RECS);
dummy:= 0;
BANKDETAILS_OBJ:=new MPLUS_MPLUS_BankGurDet_OAI_V1('',0,'',sysdate,sysdate,'');
o_RESULT:=MPLUS_MPLUS_BankGurDet_OAI_Arr();
i:=1;
LOOP
fetch RECS INTO BANKDETAILS_REC;
BANKDETAILS_OBJ.AG_CODE:=BANKDETAILS_REC.agencyname;
BANKDETAILS_OBJ.AMT_NO:=BANKDETAILS_REC.Amout;
BANKDETAILS_OBJ.BANK:=BANKDETAILS_REC.BankName;
BANKDETAILS_OBJ.VAL_FROM:=to_date(BANKDETAILS_REC.validfrom,'dd-mon-yyyy');
BANKDETAILS_OBJ.VAL_TO:=to_date(BANKDETAILS_REC.validto,'dd-mon-yyyy');
BANKDETAILS_OBJ.GUAR_NO:=BANKDETAILS_REC.guarenteeno;
o_RESULT.EXTEND;
o_RESULT(i):=BANKDETAILS_OBJ;
i:=i+1;
EXIT WHEN RECS%NOTFOUND;
END LOOP;
END imp_bankGurDet_OAI_V1;
END Mplus ;
-- The following is a legacy procedure which return a refcursor which is iterated by the implemented procedure to create object and then this object is added to VARRAY in the.
PACKAGE WF_MP_ADVT AS
PROCEDURE SP_ADV_AGE_BANK_GRTY(
          Customer_Code      IN     CHAR,
curdate in date,
          RESULT          OUT     Record_Type);
END;
PACKAGE BODY WF_MP_ADVT AS
PROCEDURE SP_ADV_AGE_BANK_GRTY(
          Customer_Code      IN     CHAR,
curdate in date,
          RESULT          OUT     Record_Type) IS
BEGIN
-- OPEN RESULT FOR SELECT AG_CODE,AMT_NO,BANK,to_char(VAL_FROM,'dd-mm-yyyy'),to_char(VAL_TO,'dd-mm-yyyy'),GUAR_NO FROM WF_MP_ADVT_BANKGAR WHERE AG_CODE=CUSTOMER_CODE;
--OPEN RESULT FOR SELECT * FROM WF_MP_ADVT_BANKGAR WHERE AG_CODE=CUSTOMER_CODE;
OPEN RESULT FOR SELECT AG_CODE,AMT_NO,BANK,to_char(VAL_FROM,'dd-mon-yyyy'),to_char(VAL_TO,'dd-mon-yyyy'),GUAR_NO FROM WF_MP_ADVT_BANKGAR WHERE AG_CODE=CUSTOMER_CODE;
-- null;
END SP_ADV_AGE_BANK_GRTY;
END;
The log file is as following
Mplus.bankGurDet:OAI/V1,OAI/V1,false,1
CUSTOMER_CODE: 1
CURRENT_DATE: Fri Oct 29 00:00:00 GMT+05:30 2004
Tue Nov 02 14:55:10 GMT+05:30 2004: InMessageTransformer: got a message for processing.
Mplus.bankGurDet:OAI/V1,OAI/V1,false,1
CUSTOMER_CODE: 1
CURRENT_DATE: Fri Oct 29 00:00:00 GMT+05:30 2004
Tue Nov 02 14:55:11 GMT+05:30 2004: Inbound Transform Engine: beginning to transform message.
Tue Nov 02 14:55:11 GMT+05:30 2004: MessageTransformer: Successfully created destination message object with necessary header information but no attribute objects yet.
Tue Nov 02 14:55:11 GMT+05:30 2004: InMessageTransformer: got a message for processing.
Mplus.bankGurDet:OAI/V1,OAI/V1,false,1
CUSTOMER_CODE: 1
CURRENT_DATE: Fri Oct 29 00:00:00 GMT+05:30 2004
Tue Nov 02 14:56:14 GMT+05:30 2004: db_bridge_writer_1 wrote the message to the database successfully.
Tue Nov 02 14:56:14 GMT+05:30 2004: Agent: sending reply message.
Mplus.bankGurDet:OAI/V1,OAI/V1,true,2
RESULT[0]
AG_CODE: 1
AMT_NO: 200000.0
BANK: STATE BANK OF INDIA
VAL_FROM: 0004-04-01
VAL_TO: 0005-03-31
GUAR_NO: SBI01
RESULT[1]
AG_CODE: 1
AMT_NO: 200000.0
BANK: HDFC BANK
VAL_FROM: 0004-04-01
VAL_TO: 0005-03-31
GUAR_NO: SBI01
RESULT[2]
AG_CODE: 1
AMT_NO: 200000.0
BANK: HDFC BANK
VAL_FROM: 0004-04-01
VAL_TO: 0005-03-31
GUAR_NO: SBI01

Vinod,
As far as I can see the problem with duplicating the last record is a result of the EXIT condition in the loop in procedure 'imp_bankGurDet_OAI_V1'. Your loop looks as follows:
LOOP
FETCH recs INTO bankdetails_rec;
bankdetails_obj.ag_code := bankdetails_rec.agencyname;
bankdetails_obj.amt_no := bankdetails_rec.amout;
bankdetails_obj.bank := bankdetails_rec.bankname;
bankdetails_obj.val_from := TO_DATE(bankdetails_rec.validfrom,'DD-MON-YYYY');
bankdetails_obj.val_to := TO_DATE(bankdetails_rec.validto,'DD-MON-YYYY');
bankdetails_obj.guar_no := bankdetails_rec.guarenteeno;
o_result.EXTEND;
o_result(i):= bankdetails_obj;
i:=i+1;
EXIT WHEN recs%NOTFOUND;
END LOOP;
The problem is that checking for recs%NOTFOUND at the end of the loop results in going through the loop one more time even though you can't fetch another row from the recs cursor. The solution is to put the EXIT condition right after the FETCH statement. You now exit the loop if you can't fetch another row without assigning the last fetched record to bankdetails_obj again:
LOOP
FETCH recs INTO bankdetails_rec;
EXIT WHEN recs%NOTFOUND;
bankdetails_obj.ag_code := bankdetails_rec.agencyname;
bankdetails_obj.amt_no := bankdetails_rec.amout;
bankdetails_obj.bank := bankdetails_rec.bankname;
bankdetails_obj.val_from := TO_DATE(bankdetails_rec.validfrom,'DD-MON-YYYY');
bankdetails_obj.val_to := TO_DATE(bankdetails_rec.validto,'DD-MON-YYYY');
bankdetails_obj.guar_no := bankdetails_rec.guarenteeno;
o_result.EXTEND;
o_result(i):= bankdetails_obj;
i:=i+1;
END LOOP;
CLOSE recs;
You also might want to consider to close the ref cursor after exiting the loop... 'too many open cursors' is not a good exception to get. ;-)
Hope this is helpful.
Thanks,
Markus

Similar Messages

  • Duplicate records returned when details come from 2 different tables

    I believe this should be a trivial case, but after days and days of experimenting, I can't get it. I'm creating a report of customers' transactions. The customer table links to a transaction header table (default join type). There are 2 tables which link to the transaction header, one for normal transaction line items, one for refunds. There is no correlation between the line items in the transaction table and those in the refund table, and they may or may not share a header. I have linked these two tables to the transaction header with left-outer-joins. What I want in the dataset, for a given transaction header, are all normal line items followed by all the refund line items (or vice versa). What I get, however, is a record for each combination of transaction details and refund details, whenever they share a common header. So, for example, if I have transaction line items 1, 2, 3, and 4 for a given header, plus refund lines A and B for the same header (as might happen if a customer returned 2 products at the same time he bought 4), what I want is a data set of 1,2,3,4,A,B. Instead, what I get is 1A,1B,2A,2B,3A,3B,4A,4B.
    How can I get the result I need? Is this simply a join issue, or must I weed out the duplication using complex formula scripts? Or a subreport? Or something else?
    thanks.
    John

    Subreport would solve this problem but it sub-report take a long time export. Does anyone know how to integrate subreport without suffering the performance lost?
    My report have two subreport and everytime I tried to export the value it take ages to export. My database is only about 20k items and it take almost 10 min to export.
    Does any one know how to make this process faster?

  • Using Rownum and ROwid returns duplicate records

    Hi All,
    We have implemented pagination as below using rowid and rownum
    SELECT
    id
    FROM
    emp
    WHERE
    ROWID IN
    SELECT RID FROM (SELECT
    ROWID RID,
    ROWNUM RNUM
    FROM
    SELECT ID FROM emp
    WHERE
    ((T_ID IN (200005,200229,200230,200249,200250,200049))) AND
    (dte >= sysdate-90) AND
    (LOWER(DESC) = LOWER ('A') AND
    LOWER(NVL(FLAG,'0')) != LOWER ('3') AND
    LOWER(MODDE) like LOWER ('%210%')) ORDER BY dte ASC ))
    WHERE ROWNUM < 11) WHERE RNUM>= 1)) ORDER BY dte emp.ASC
    But, we face that - the query inserts duplicate records in consecutive pages. For Eg:
    1.if a,b,c,d,e - is returned for first iteration, then for the next iteration - f,g,h,a,y is returned.
    Is it because that the Order by clause doesnt have a Unique key column.
    Please help. or suggest how to efficietly implement pagination without performance hit

    try distinct since you are using only one column it will eliminate any duplicates.
    SELECT distinct id
      FROM emp
    WHERE (ROWID IN ( SELECT RID
                         FROM (SELECT ROWID RID,ROWNUM RNUM
                                 FROM (SELECT ID
                                         FROM emp
                                        WHERE ((T_ID IN (200005,200229,200230,200249,200250,200049)))
                                          AND (dte >= sysdate-90)
                                          AND (LOWER(DESC) = LOWER ('A')
                                          AND LOWER(NVL(FLAG,'0')) != LOWER ('3')
                                          AND LOWER(MODDE) like LOWER ('%210%'))
                                       ORDER BY dte ASC ))
                                WHERE ROWNUM < 11) 
                        WHERE RNUM>= 1))
    ORDER BY dte emp.ASC

  • Return all duplicate record

    hi how can i return all duplicate records, not just the records which is duplicate, can you check my query
    select c_code,facility_name,npo_registration_no,AGR.CONTRACT_NO
    ,ssch.name subsidy,SSCH.SUB_PROGRAMME, organisation,opex_allocation
    from sms_parties par
    ,sms_agreements agr
    ,SMS_SUBSIDY_SCHEMES_VW ssch
    ,sms_agreement_years ayea
    ,sms_agreement_status asta
    ,sms_fyea_open_vw fyea
    where par.id = agr.par_id
    and agr.id = ayea.id (+)
    and agr.contract_no like '%2011%'
    and ayea.asta_id = asta.id (+)
    and agr.ssch_id = SSCH.SSCH_ID
    and npo_registration_no in (
    select npo_registration_no
    from sms_parties
    group by npo_registration_no
    having count(*) > 1
    order by 1
    Edited by: user603350 on 2011/08/25 5:30 PM

    select *
    from (
      select c_code
            ,facility_name
            ,npo_registration_no
            ,AGR.CONTRACT_NO
            ,ssch.name subsidy
            ,SSCH.SUB_PROGRAMME
            ,organisation
            ,opex_allocation
            ,row_number() over ( partition by c_code
                                          ,facility_name
                                          ,npo_registration_no
                                          ,AGR.CONTRACT_NO
                                          ,ssch.name subsidy
                                          ,SSCH.SUB_PROGRAMME
                                          ,organisation
                                          ,opex_allocation
                                 order by npo_registration_no) rn
            ,count(1) over ( partition by c_code
                                          ,facility_name
                                          ,npo_registration_no
                                          ,AGR.CONTRACT_NO
                                          ,ssch.name subsidy
                                          ,SSCH.SUB_PROGRAMME
                                          ,organisation
                                          ,opex_allocation) cn
      from   sms_parties par
            ,sms_agreements agr
            ,SMS_SUBSIDY_SCHEMES_VW ssch
            ,sms_agreement_years ayea
            ,sms_agreement_status asta
            ,sms_fyea_open_vw fyea
      where  par.id             = agr.par_id
      and    agr.id             = ayea.id (+)
      and    agr.contract_no    like '%2011%'
      and    ayea.asta_id       = asta.id (+)
      and    agr.ssch_id = SSCH.SSCH_ID
    where rn != 1
    and   cn > 1
    order by 1or
    select *
    from (
      select c_code
            ,facility_name
            ,npo_registration_no
            ,AGR.CONTRACT_NO
            ,ssch.name subsidy
            ,SSCH.SUB_PROGRAMME
            ,organisation
            ,opex_allocation
            ,row_number() over ( partition by npo_registration_no
                                 order by npo_registration_no) rn
            ,count(1) over ( partition by npo_registration_no) cn
      from   sms_parties par
            ,sms_agreements agr
            ,SMS_SUBSIDY_SCHEMES_VW ssch
            ,sms_agreement_years ayea
            ,sms_agreement_status asta
            ,sms_fyea_open_vw fyea
      where  par.id             = agr.par_id
      and    agr.id             = ayea.id (+)
      and    agr.contract_no    like '%2011%'
      and    ayea.asta_id       = asta.id (+)
      and    agr.ssch_id = SSCH.SSCH_ID
    where rn != 1
    and   cn > 1
    order by 1Included both as I'm not sure about your logic, but you'll have to play around with the PARTITION BY window.
    UNETSTED!

  • USE of PREVIOUS command to eliminate duplicate records in counter formula

    i'm trying to create a counter formula to count the number of documents paid over 30 days.  to do this i have to subtract the InvDate from the PayDate.   and then create a counter based on this value.  if {days to pay} is greater than 30 then 1 else 0.
    then sum the {days to pay} field to each group.   groups are company, month, and supplier.
    becuase invoices can have multiple payments and payments can have multiple invoices. there is no way around having duplicate records for the field. 
    so my counter is distorted by by the duplicate records and my percentage of payments over 30 days formula will not be accurate do to these duplicates.
    I've tried Distinct Count based on this formula  if {days to pay} is greater than 30 then . and it works except that is counts 0.00 has a distinct records so my total is off 1 for summaries with a record that (days to pay} is less than or equal to 30.
    if i subract 1 from the formula then it will be inaccurate for summaries with no records over 30 days.
    so i'm come to this.
    if Previous() do not equal
    then
      if {day to days} greater than 30
      then 1
      else 0.00
    else 0.00
    but it doesn't work.  i've sorted the detail section by
    does anyone have any knowledge or success using the PREVIOUS command in a report?
    Edited by: Fred Ebbett on Feb 11, 2010 5:41 PM

    So, you have to include all data and not just use the selection criteria 'PayDate-InvDate>30'?
    You will need to create a running total on the RPDOC ID, one for each section you need to show a count for, evaluating for your >30 day formula. 
    I don't understand why you're telling the formula to return 0.00 in your if statement.
    In order to get percentages you'll need to use the distinct count (possibly running totals again but this time no formula). Then in each section you'd need a formula that divides the two running totals.
    I may not have my head around the concept since you stated "invoices can have multiple payments and payments can have multiple invoices".  So, invoice A can have payments 1, 2 and 3.  And Payment 4 can be associated with invoice B and C?  Ugh.  Still though, you're evaluating every row of data.  If you're focus is the invoices that took longer than 30 days to be paid...I'd group on the invoice number, put the "if 'PayDate-InvDate>30' then 1 else 0" formula in the detail, do a sum on it in the group footer and base my running total on the sum being >0 to do a distinct count of invoices.
    Hope this points you in the right direction.
    Eric

  • Duplicate records problem

    Hi everyone,
    I'm having a a little difficulty resolving a problem with a repeating field causing duplication of data in a report I'm working on, and was hoping someone on here can suggest something to help!
    My report is designed to detail library issues during a particular period, categorised by the language of the item issued. My problem is that on the sql database that out library management system uses, it is possible for an item to have more than one language listed against it (some books will be in more than one language). When I list the loan records excluding the language data field, I get a list of distinct loan records. Bringing the language data into the report causes the loan record to repeat for each language associated with it, so if a book is both in English and French, it will cause the loan record to appear like this:
    LOAN RECORD NO.     LANGUAGE CODE
      123456                             ENG
      123456                             FRE
    So, although the loan only occurred once I have two instances of it in my report.
    I am only interested in the language that appears first and I can exclude duplicated records from the report page. I can also count only the distinct records to get an accurate overall total. My problem is that when I group the loan records by language code (I really need to do this as there are millions of loan records held in the database) the distinct count stops being a solution, as when placed at this group level it only excludes duplicates in the respective group level it's placed in. So my report would display something like this:
    ENG     1
    FRE      1
    A distinct count of the whole report would give the correct total of 1, but a cumulative total of the figures calculated at the language code group level would total 2, and be incorrect. I've encountered similar results when using Running Totals evaluating on a formula that excludes repeated loan record no.s from the count, but again when I group on the language code this goes out of the window.
    I need to find a way of grouping the loan records by language with a total count of loan records alongside each grouping that accurately reflects how many loans of that language took place.
    Is this possible using a calculation formula when there are repeating fields, or do I need to find a way of merging the repeating language fields into one field so that the report would appear like:
    LOAN RECORD     LANGUAGE CODE
      123456                      ENG, FRE
    Any suggestions would be greatly appreciated, as aside from this repeating language data there are quite a few other repeating database fields on the system that it would be nice to report on!
    Thanks!

    if you create a group by loan
    then create a group by language
    place the values in the group(loan id in the loan header)
    you should only see the loan id 1x.
    place the language in the language group you should only see that one time
    a group header returns the 1st value of a unique id....
    then in order to calculate avoiding the duplicates
    use manual running totals
    create a set for each summary you want- make sure each set has a different variable name
    MANUAL RUNNING TOTALS
    RESET
    The reset formula is placed in a group header report header to reset the summary to zero for each unique record it groups by.
    whileprintingrecords;
    Numbervar  X := 0;
    CALCULATION
    The calculation is placed adjacent to the field or formula that is being calculated.
    (if there are duplicate values; create a group on the field that is being calculated on. If there are not duplicate records, the detail section is used.
    whileprintingrecords;
    Numbervar  X := x + ; ( or formula)
    DISPLAY
    The display is the sum of what is being calculated. This is placed in a group, page or report footer. (generally placed in the group footer of the group header where the reset is placed.)
    whileprintingrecords;
    Numbervar  X;
    X

  • Script to merge multiple CSV files together with no duplicate records.

    I like a Script to merge multiple CSV files together with no duplicate records.
    None of the files have any headers and column A got a unique ID. What would be the best way to accomplish that?

    OK here is my answer :
    2 files in a directory with no headers.
    first column is the unique ID, second colomun you put whatever u want
    The headers are added when using the import-csv cmdlet
    first file contains :
    1;a
    2;SAMEID-FIRSTFILE
    3;c
    4;d
    5;e
    second file contains :
    6;a
    2;SAMEID-SECONDFILE
    7;c
    8;d
    9;e
    the second file contains the line : 2;b wich is the same in the first file
    the code :
    $i = 0
    Foreach($file in (get-childitem d:\yourpath)){
    if($i -eq 0){
    $ref = import-csv $file.fullname -Header id,value -Delimiter ";"
    }else{
    $temp = import-csv $file.fullname -Header id,value -Delimiter ";"
    foreach($line in $temp){
    if(!($ref.id.contains($line.id))){
    $objet = new-object Psobject
    Add-Member -InputObject $objet -MemberType NoteProperty -Name id -value $line.id
    Add-Member -InputObject $objet -MemberType NoteProperty -Name value -value $line.value
    $ref += $objet
    $i++
    $ref
    $ref should return:
    id                                                         
    value
    1                                                          
    a
    2                                                          
    SAMEID-FIRSTFILE
    3                                                          
    c
    4                                                          
    d
    5                                                          
    e
    6                                                          
    a
    7                                                          
    c
    8                                                          
    d
    9                                                          
    e
    (get-childitem d:\yourpath) -> yourpath containing the 2 csv file

  • Problem with duplicate records..

    Hi..I am trying to insert the records to the database based on a button click from a Swing frame..I have succeeded in that...But when i try to insert a duplicate record it is showing com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 1
    My code is
    import java.awt.event.*;
    import java.sql.*;
    public class BarcodeReader extends javax.swing.JFrame implements ActionListener {
        static Connection con;
        static String url = "jdbc:mysql://localhost:3306/";
        static String db = "mynewdatabase";
        static String driver = "com.mysql.jdbc.Driver";
        static String user = "uname";
        static String pass = "pwd";
        static Statement stmt;
        /** Creates new form BarcodeReader */
        public BarcodeReader() {
            initComponents();
            nb.addActionListener(this);
        public static Connection getConnection(){
            try{
                Class.forName(driver);
                con = DriverManager.getConnection(url + db, user, pass);
                stmt=con.createStatement();
                System.out.println("jdbc driver for mysql : " + driver);
                System.out.println("Connection url : " + url + db);
                }catch (Exception ex)
                   ex.printStackTrace();
            return con;
    private void ActionPerformed(java.awt.event.ActionEvent evt) {                                
            Connection con=getConnection();
            String t=newtxt.getText();
            int t1=Integer.parseInt(t);
            try{
                PreparedStatement p=con.prepareStatement("INSERT INTO machine(barcode) values(?)");
                ResultSet rs=stmt.executeQuery("SELECT * FROM MACHINE");
                while(rs.next()){
                    String s=rs.getString("barcode");
                   if(s.equals(t))
                      System.out.println("this id exists....");
                        rs.last();
                   p.setInt(1, t1);
                   p.executeUpdate();
                   new NewJFrame().setVisible(true);
            }catch(Exception e){
                e.printStackTrace();
    public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new BarcodeReader().setVisible(true);
        }When i insert a new record is ok, but when i am inserting the same record again it shows the following exception..
    jdbc driver for mysql : com.mysql.jdbc.Driver
    Connection url : jdbc:mysql://localhost:3306/mynewdatabase
    this id exists....
    com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 1
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
            at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
            at com.mysql.jdbc.Util.getInstance(Util.java:381)
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3536)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3468)
            at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1957)
            at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2107)
            at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648)
            at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2086)
            at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2371)
            at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2289)
            at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2274)
            at project.BarcodeReader.ActionPerformed(BarcodeReader.java:276)
            at project.BarcodeReader.access$000(BarcodeReader.java:17)
            at project.BarcodeReader$1.actionPerformed(BarcodeReader.java:138)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6263)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
            at java.awt.Component.processEvent(Component.java:6028)
            at java.awt.Container.processEvent(Container.java:2041)
            at java.awt.Component.dispatchEventImpl(Component.java:4630)
            at java.awt.Container.dispatchEventImpl(Container.java:2099)
            at java.awt.Component.dispatchEvent(Component.java:4460)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
            at java.awt.Container.dispatchEventImpl(Container.java:2085)
            at java.awt.Window.dispatchEventImpl(Window.java:2475)
            at java.awt.Component.dispatchEvent(Component.java:4460)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)Thanks.

    shelton141 wrote:
    Hi..I am trying to insert the records to the database based on a button click from a Swing frame..I have succeeded in that...But when i try to insert a duplicate record it is showing com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 1Of course it is. That is what it is suppossed to do.
    Try inserting the same record twice, manually, and see what happens.
    There is however, if I remember right, an "IGNORE" "clause/option/whatever" that you can use on INSERT statements in MySQL. Check the manual, if that is what you really want.

  • Duplicate Records in Output

    I have a script which works fine however what I cant seem to work out is why I get duplicate records in the output. If anyone knows why it would be a great help/
    My code is below:
    Connect-QADService "domain.com"
    Function CheckUserExistance {
    if(Get-QADUser -Identity $Global:Sam) {
    Write-Host "User Found: $Global:Sam"
    $Example = $Global:Sam + "2"
    $prompt = "This User Already Exists, Please Choose Another Name. (e.g. $Example)"
    $Title = "Error"
    Add-Type -AssemblyName microsoft.visualbasic
    $popup = [Microsoft.VisualBasic.interaction]::MsgBox($prompt,"OkOnly,Critical", $title)
    if ($popup -eq "Ok"){
    $prompt = "Please Enter The Name To Create (All Lowercase e.g john.smith):"
    $Title = "User To Create"
    Add-Type -AssemblyName microsoft.visualbasic
    $Global:Sam = [Microsoft.VisualBasic.interaction]::inputbox($prompt,$title)
    if ($Global:Sam -eq ""){exit}
    # The following Function is used to randomly generate complex passwords.
    function New-Password
    param
    [int]$length,
    [switch]$lowerCase,
    [switch]$upperCase,
    [switch]$numbers,
    [switch]$specialChars
    BEGIN
    # Usage Instructions
    function Usage()
    Write-Host ''
    Write-Host 'FUNCTION NAME: New-Password' -ForegroundColor White
    Write-Host ''
    Write-Host 'USAGE'
    Write-Host ' New-Password -length 10 -upperCase -lowerCase -numbers'
    Write-Host ' New-Password -length 10 -specialChars'
    Write-Host ' New-Password -le 10 -lo -u -n -s'
    Write-Host ' New-Password'
    Write-Host ''
    Write-Host 'DESCRIPTION:'
    Write-Host ' Generates a random password of a given length (-length parameter)'
    Write-Host ' comprised of at least one character from each subset provided'
    Write-Host ' as a switch parameter.'
    Write-Host ''
    Write-Host 'AVAILABLE SWITCHES:'
    Write-Host ' -lowerCase : include all lower case letters'
    Write-Host ' -upperCase : include all upper case letters'
    Write-Host ' -numbers : include 0-9'
    Write-Host ' -specialChars : include the following- !@#$%^&*()_+-={}[]<>'
    Write-Host ''
    Write-Host 'REQUIREMENTS:'
    Write-Host ' You must provide the -length (four or greater) and at least one character switch'
    Write-Host ''
    function generate_password
    if ($lowerCase)
    $charsToUse += $lCase
    $regexExp += "(?=.*[$lCase])"
    if ($upperCase)
    $charsToUse += $uCase
    $regexExp += "(?=.*[$uCase])"
    if ($numbers)
    $charsToUse += $nums
    $regexExp += "(?=.*[$nums])"
    if ($specialChars)
    $charsToUse += $specChars
    $regexExp += "(?=.*[\W])"
    $test = [regex]$regexExp
    $rnd = New-Object System.Random
    do
    $pw = $null
    for ($i = 0 ; $i -lt $length ; $i++)
    $pw += $charsToUse[($rnd.Next(0,$charsToUse.Length))]
    Start-Sleep -milliseconds 20
    until ($pw -match $test)
    return $pw
    # Displays help
    if (($Args[0] -eq "-?") -or ($Args[0] -eq "-help"))
    Usage
    break
    else
    $lCase = 'abcdefghijklmnopqrstuvwxyz'
    $uCase = $lCase.ToUpper()
    $nums = '1234567890'
    $specChars = '!@#$%^&*()_+-={}[]<>'
    PROCESS
    if (($length -ge 4) -and ($lowerCase -or $upperCase -or $numbers -or $specialChars))
    $newPassword = generate_password
    else
    Usage
    break
    $newPassword
    END
    Import-Csv "C:\ExternalADAccounts.csv" |
    ForEach-Object {
    $First = $_.Forename
    $Last = $_.Surname
    $Password = New-Password -length 8 -upperCase -lowerCase -numbers -specialChars
    $stuff = $_.stuff
    $OU = "domain.com/ou"
    $UPN = "$First.$Last@$stuff.domain.com"
    $Global:Sam = "$First.$Last"
    $Display = "$First $Last"
    $Global:Sam = $Global:Sam -Replace " ", ""
    $Global:Sam = $Global:Sam -Replace "'",""
    $Count = $Global:Sam.Length
    If($Count -gt "19"){
    $Global:Sam = $First[0] + "." + $Last
    Do{CheckUserExistance}
    While(Get-QADUser -Identity $Global:Sam)
    Write-Host "Creating User: $Global:Sam"
    New-QADUser -FirstName $First `
    -LastName $Last `
    -DisplayName $Display `
    -Name $Global:Sam `
    -SamAccountName $Global:Sam.ToLower() `
    -UserPassword $Password `
    -UserPrincipalName $UPN.ToLower() `
    -ParentContainer $OU
    do{
    $Test = Get-QADUser -Identity $Global:Sam
    } until(Get-QADUser -Identity $Global:Sam)
    Set-QADUser $Global:Sam -Title 'Non-Managed'
    } | Select-Object @{label="DisplayName";expression={$Display}},@{label="SamAccountName";expression={$Global:Sam}}, @{label="Password";expression={$Password}}, @{label="Stuff";expression={$Stuff}} |
    Sort-Object $Stuff |
    Export-Csv "C:\NonManagedCreated.csv" -NoTypeInformation
    Any help is greatly appreciated.
    James

    Hi James,
    Please try the script below, which will use Psobject to format the output:
    $output=@()##########
    Import-Csv "C:\ExternalADAccounts.csv" |
    ForEach-Object {
    do{
    $Test = Get-QADUser -Identity $Global:Sam
    } until(Get-QADUser -Identity $Global:Sam)
    Set-QADUser $Global:Sam -Title 'Non-Managed'
    ###########output
    $Object = New-Object -TypeName PSObject
    $object | Add-Member -Name 'DisplayName' -MemberType Noteproperty -Value $DisplayName
    $object | Add-Member -Name 'SamAccountName' -MemberType Noteproperty -Value $Global:Sam
    $object | Add-Member -Name 'Password' -MemberType Noteproperty -Value $Password
    $object | Add-Member -Name 'Stuff' -MemberType Noteproperty -Value $Stuff
    $output+=$Object
    $output|select DisplayName,SamAccountName,Password,Stuff| Sort-Object Stuff |Export-Csv "C:\NonManagedCreated.csv" -NoTypeInformation
    If there s anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang

  • How to avoid duplicate record in a file to file

    Hi Guys,
              Could you please provide a soultion
              in order  to avoid duplicate entries in a flat file based on key field.
              i request in terms of standard functions
             either at message mappingf level or by configuring the file adapter.
    warm regards
    mahesh.

    hi mahesh,
    write module processor for checking the duplicate record in file adapter
    or
    With a JAVA/ABAP mapping u can eliminate the duplicate records
    and check this links
    Re: How to Handle this "Duplicate Records"
    Duplicate records
    Ignoring Duplicate Records--urgent
    Re: Duplicate records frequently occurred
    Re: Reg ODS JUNK DATA
    http://help.sap.com/saphelp_nw2004s/helpdata/en/d0/538f3b294a7f2de10000000a11402f/frameset.htm
    regards
    srinivas

  • Need to include duplicate records in sub query

    Hi All,
             I am using the following query and i am getting error message that your sub query return dupliate records and throwing error. Actually i need these duplicate records for my report. I want to get records for
    whole year like
       JAN FEB MARCH ..   ...    ...
    and idea how i can achieve this task and my query is as follows
     select pmnum
     ,SITEID,
     (select description from locations where pm.location = locations.location and pm.siteid=locations.siteid) as site,
     (select description from commodities where commodities.commodity=  pm.commoditygroup) as workcategory,
     description, (select wonum from workorder where workorder.pmnum = pm.pmnum
     and  targstartdate < '2013-02-01') as jan,
     (select wonum from workorder where workorder.pmnum = pm.pmnum and
     workorder.status<>'CAN' and targstartdate >= '2013-02-01' and
     targstartdate < '2013-03-01') as feb,
     (select wonum from workorder where workorder.pmnum = pm.pmnum and
     workorder.status<>'CAN' and targstartdate >= '2013-03-01' and
     targstartdate < '2013-04-01') as mar
    (select name from companies where companies.company = pm.vendor) as contractor 
           from pm  where ((PM.siteid = 'AAA'))

    Subqueries in the SELECT column list must return a scalar value (single row, single column).  If you need multiple rows returned, use a join instead.  But you need to consider what will happen when more than one row is returned by more than one
    of the joins because these are correlated with the pm table row but not each other.  For example, let's say you have a single row returned from "pm" matching 5 sites and 3 workcategories.  This will result in 15 rows being returned for the single
    pm row.
    Below is an untested example.
    SELECT
    pmnum
    ,SITEID
    ,locations.description as site
    ,commodities.description as workcategory
    ,pm.description
    ,workorder_jan.wonum AS jan
    ,workorder_feb.wonum AS feb
    ,workorder_mar.wonum AS mar
    ,companies.name AS contractor
    FROM dbo.pm
    LEFT JOIN dbo.locations ON pm.location = locations.location
    AND pm.siteid=locations.siteid
    LEFT JOIN dbo.commodities ON commodities.commodity = pm.commoditygroup
    LEFT JOIN dbo.workorder AS workorder_jan ON workorder_jan.pmnum = pm.pmnum
    AND workorder_jan.targstartdate < '2013-02-01'
    LEFT JOIN dbo.workorder AS workorder_feb ON workorder_feb.pmnum = pm.pmnum
    AND workorder_feb.status <> 'CAN'
    AND workorder_feb.targstartdate >= '2013-02-01'
    AND workorder_feb.targstartdate < '2013-03-01'
    LEFT JOIN dbo.workorder AS workorder_mar ON workorder_mar.pmnum = pm.pmnum
    AND workorder_mar.status <> 'CAN'
    AND workorder_mar.targstartdate >= '2013-03-01'
    AND workorder_mar.targstartdate < '2013-04-01'
    LEFT JOIN dbo.companies ON companies.company = pm.vendor
    WHERE pm.siteid = 'AAA';
    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

  • Join retrieving duplicate records

    Can someone tell me why I am returning 10 records when there only should be one. I can put in a delete duplicates record after this but i would prefer to know what is wrong with the below. Tnks.
      SELECT MARAMATNR MARAPRDHA
             MAKTMAKTX T179TVTEXT
             APPENDING CORRESPONDING FIELDS OF TABLE GT_WK_STORAGE
             FROM MARA AS MARA
             INNER JOIN MAKT AS MAKT
             ON MARAMATNR EQ MAKTMATNR
             AND SPRAS EQ SY-LANGU
             INNER JOIN T179T AS T179T
             ON MARAPRDHA EQ T179TPRODH
             WHERE MARA~MATNR IN S_MATNR.

    Hi,
    I see one error in your code:
    +FROM MARA AS MARA
    INNER JOIN MAKT AS MAKT
    ON MARAMATNR EQ MAKTMATNR
    AND SPRAS EQ SY-LANGU+
    how can you pretend to join tables MARA and MAKT with field SPRAS, when this field does not exist in MARA ??
    I think you should modify your code this way:
    SELECT MATNR PRDHA
    into CORRESPONDING FIELDS OF GT_WK_STORAGE
    from mara
    WHERE MATNR IN S_MATNR.
    SELECT single MAKTMAKTX T179TVTEXT
    into CORRESPONDING FIELDS OF GT_WK_STORAGE
    FROM makt inner join T179T
    ON MAKTSPRAS EQ T179TSPRAS
    WHERE MAKT~MATNR = GT_WK_STORAGE-MATNR
    and   spras = sy-langu.
    append GT_WK_STORAGE.
    endselect.
    Check the code, that I didn´t do it in SAP.

  • Error RSMPTEXTS~:Duplicate record dur durin EHP5 in phase SHADOW_IMPORT_INC

    Hi expert,
    i find this error during an EHP5 upgrade in phase shadow_import_inc:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    SHADOW IMPORT ERRORS and RETURN CODE in SAPK-701DOINSAPBASIS.ERD
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    2EETW000 Table RSMPTEXTS~: Duplicate record during array insert occured.
    2EETW000 Table RSMPTEXTS~: Duplicate record during array insert occured.
    1 ETP111 exit code           : "8"
    here also the last part of log SAPK-701DOINSAPBASIS.ERD
    4 ETW000 Totally 4 tabentries imported.
    4 ETW000 953984 bytes modified in database.
    4 ETW000  [     dev trc,00000]  Thu Aug 11 16:58:45 2011                                             7954092  8.712985
    4 ETW000  [     dev trc,00000]  Disconnecting from ALL connections:                                       28  8.713013
    4 ETW000  [     dev trc,00000]  Disconnecting from connection 0 ...                                       38  8.713051
    4 ETW000  [     dev trc,00000]  Closing user session (con=0, svc=0000000005C317C8, usr=0000000005C409A0)
    4 ETW000                                                                                8382  8.721433
    4 ETW000  [     dev trc,00000]  Detaching from DB Server (con=0,svchp=0000000005C317C8,srvhp=0000000005C32048)
    4 ETW000                                                                                7275  8.728708
    4 ETW000  [     dev trc,00000]  Now I'm disconnected from ORACLE                                        8648  8.737356
    4 ETW000  [     dev trc,00000]  Disconnected from connection 0                                            84  8.737440
    4 ETW000  [     dev trc,00000]  statistics db_con_commit (com_total=13, com_tx=13)                        18  8.737458
    4 ETW000  [     dev trc,00000]  statistics db_con_rollback (roll_total=0, roll_tx=0)                      14  8.737472
    4 ETW000 Disconnected from database.
    4 ETW000 End of Transport (0008).
    4 ETW000 date&time: 11.08.2011 - 16:58:45
    4 ETW000 1 warning occured.
    4 ETW000 1 error occured.
    1 ETP187 R3TRANS SHADOW IMPORT
    1 ETP110 end date and time   : "20110811165845"
    1 ETP111 exit code           : "8"
    1 ETP199 ######################################
    4 EPU202XEND OF SECTION BEING ANALYZED IN PHASE SHADOW_IMPORT_INC
    and i've already try to use the last version of R3trans.
    can you help me????
    thanks a lot
    Franci

    Hello Fransesca,
    I am also facing same error while upgrading ehp5 upgradation please if you know tell me steps to solve it.
    Thanks,
    Venkat

  • Help with Finding Duplicate records Query

    HI,
    I am trying to write a query that will find duplicate records/cases.
    This query will be used in a report.
    So, here are the requirements:
    I need to find duplicate cases/records based on the following fields:
    DOB, DOCKET, SENT_DATEI was able to do that with the following query. The query below is able to give me all duplicate records based on the Criteria above
    SELECT      DEF.BIRTH_DATE DOB,
               S.DOCKET DOCKET,
               S.SENT_VIO_DATE SENT_DATE, COUNT(*)
    FROM SENTENCES S,
                DEFENDANTS DEF
    WHERE      S.DEF_ID = DEF.DEF_ID
    AND       S.CASE_TYPE_CODE = 10
    GROUP BY  DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE
    HAVING COUNT(*) > 1;
    //I AM GOING TO CALL THIS QUERY 'X'Now, the information to be displayed on the report: defendants Name, DOB, District, Docket, Def Num, Sent Date, and PACTS Num if possible.
    The problem that I need help on is how to combine those queries together (what I mean is a sub query). the 'X' query returns multiple values. please have a look at the comments on the query below to see what I'm trying to achieve.
    here is the main query:
    SELECT      INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
    FROM      USSC_CASES.DEFENDANTS DEF,
            USSC_CASES.SENTENCES S,
            LOOKUP.DISTRICTS DIST
    WHERE      DEF.DEF_ID = S.DEF_ID
    AND      S.DIST_ID = DIST.USSC_DISTRICT_ID
    AND     S.CASE_TYPE_CODE = 10
    AND     S.USSC_ID IS NOT NULL
    AND // what i'm trying to do is: DOB, DOCKET, SENT_DATE IN ('X' QUERY), is this possible ??
    ORDER BY DEFENDANT_NAME; thanks in advance.
    I am using Oracle 11g, and sql developer.
    if my approach doesn't work, is there a better approach ?
    Edited by: Rooney on Jul 11, 2012 3:50 PM

    If I got it right, you want to join table USSC_CASES.DEFENDANTS to duplicate rows in USSC_CASES. If so:
    SELECT  INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
      FROM  USSC_CASES.DEFENDANTS DEF,
             SELECT  *
               FROM  (
                      SELECT  S.*,
                              COUNT(*) OVER(PARTITION BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE) CNT
                        FROM  USSC_CASES.SENTENCES S
               WHERE CNT > 1
            ) S,
            LOOKUP.DISTRICTS DIST
      WHERE DEF.DEF_ID = S.DEF_ID
       AND  S.DIST_ID = DIST.USSC_DISTRICT_ID
       AND  S.CASE_TYPE_CODE = 10
       AND  S.USSC_ID IS NOT NULL
      ORDER BY DEFENDANT_NAME;If you want to exclude duplicates from the query and do not care which row out of duplicate rows to choose:
    SELECT  INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
      FROM  USSC_CASES.DEFENDANTS DEF,
             SELECT  *
               FROM  (
                      SELECT  S.*,
                              ROW_NUMBER() OVER(PARTITION BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE ORDER BY 1) RN
                        FROM  USSC_CASES.SENTENCES S
               WHERE RN = 1
            ) S,
            LOOKUP.DISTRICTS DIST
      WHERE DEF.DEF_ID = S.DEF_ID
       AND  S.DIST_ID = DIST.USSC_DISTRICT_ID
       AND  S.CASE_TYPE_CODE = 10
       AND  S.USSC_ID IS NOT NULL
      ORDER BY DEFENDANT_NAME;SY.

  • Duplicate Record Search

    I need help with the SQL Statement below.
    SELECT DISTINCT RISK_CODE, LOB, COMPANY, STATE, RISK_CODE_DESCR, RISK_CODE_QUESTION_TEXT, EXPECTED_RESULT
    FROM RISK_CODE
    WHERE RISK_CODE_QUESTION_TEXT IS NOT NULL
    AND ASK_INDICATOR = 'Y'
    AND LOB = 'P1'
    AND ((COMPANY = '' OR COMPANY IS NULL)
    OR (STATE = '' OR STATE IS NULL))
    I want to return the values (risk code questions) when there is a company number and where there isn't, and the same for state. The problem that I run into, is when I do have a company number (ex: 077) and a state (ex. 04), I simply return duplicate values back, and I wanted to know if there was a way to avoid that.
    Not only do I need the values from a specific record (with Company and State), but I also need the records that are not company and state specific. A sample of the data is below.
    RISK_CODE - LOB - COMPANY - STATE - RISK_CODE_DESCR
    74 - P1 - 077 - 04 - DESCRIPTION1
    74 - P1 - - - DESCRIPTION1
    01 - P1 - 077 - 04 - DESCRIPTION2
    01 - P1 - - - DESCRIPTION2
    02 - P1 - - - DESCRIPTION3
    TY - P1 - - - DESCRIPTION4
    U7 - P1 - 077 - 04 - DESCRIPTION5
    I don't know if this helps or not, but if I pass in the state and company I would need risk codes 74, 01, 02, and TY. But if I pass the state and company I would need 74, 01, 02, TY, and U7. I don't want duplicate records back, and don't want to have to create a huge stored procedure for this.

    What duplicate values are you getting? From looking at you data I don't think you're getting duplicate values. What you are getting is the values for risk_code when there is a state populated and when then isn't. This is of course exactly what you've asked for.
    Presumably the RISK_CODE_DESCR are different and that's why your DISTINCT isn't filtering them.
    What you need to do is soemthing like this:
    SELECT RISK_CODE, LOB, COMPANY, STATE, RISK_CODE_DESCR, RISK_CODE_QUESTION_TEXT, EXPECTED_RESULT
    FROM RISK_CODE
    WHERE RISK_CODE_QUESTION_TEXT IS NOT NULL
    AND ASK_INDICATOR = 'Y'
    AND LOB = 'P1'
    AND ( COMPANY = '&&IN_CO' OR
          STATE = '&&IN_STATE')
    UNION
    SELECT RISK_CODE, LOB, COMPANY, STATE, RISK_CODE_DESCR, RISK_CODE_QUESTION_TEXT, EXPECTED_RESULT
    FROM RISK_CODE
    WHERE RISK_CODE_QUESTION_TEXT IS NOT NULL
    AND ASK_INDICATOR = 'Y'
    AND LOB = 'P1'
    AND COMPANY IS NULL
    AND STATE IS NULL
    AND NOT EXISTS (SELECT  RISK_CODE
                    FROM RISK_CODE
                    WHERE RISK_CODE_QUESTION_TEXT IS NOT NULL
                    AND ASK_INDICATOR = 'Y'
                    AND LOB = 'P1'
                    AND ( COMPANY = '&&IN_CO' OR
                          STATE = '&&IN_STATE')).
    Mind you, I'm not saying it's pretty or fast.
    Cheers, APC

Maybe you are looking for

  • Order Confirmation Without Doing Goods Issue & No Goods Receipt W/o Confirm

    Hi,      I am facing a problem at client site & i need a quick response from you people. If i am not doing GOODS ISSUE to a Production Order the system is allowing me to do Confirmation for that Production order & also the system is allowing me to do

  • Loading transactional data before go live

    Dear colleagues, In my actual project we have an unexpected and strange requirement wich is to load all the postings that they have done during the year before go-live in their legacy system (we are going live on may). Therefore we have divided the i

  • Are plain text files treated differently in SP 2010 than MOSS 2007?

    We just moved to SP 2010 a week ago.  A user just contacted us asking why the files she accesses are not displaying. When she accessed these plain text files in MOSS 2007, they displayed within IE as a full page of text. When she accesses these now i

  • Premier Elements 7.0

    I've installed Premier Elements 7.0.  No Problem.  When I connect my camera to my PC to do video capture it activates the old Premier Elements 4 program.  The Read Before Installing file says we can keep old versions loaded but not to run simultaneou

  • Lightroom from a PC to a MAC

    I have both Lightroom and Photoshop on my PC laptop. Well now I am in the market to buy a MAC, but do I have to buy new softwear again or is there any way to instal it on to a MAC?