How to compare record count of two tables?

Hi,
i am in need of simple sql script where i can compare two table record count.
i have something like below:
(select count(*) from table1) minus (select count(*) from table2)
now the problem is if the table1 count greater then table2 count the output is fine.
If the table2 record count is more then i am getting zero as the output.
how can i get the difference in two tables record count?
Thanks a lot in advance.
--Raman.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Doing a MINUS between the counts does not yield the diff.
e.g. if table A has 100 records and table B has 70 records then,
SELECT count(*) FROM A
minus
SELECT count(*) from B
will give 100 and not 30.
Try this:
SELECT (
CASE WHEN ((select count(*) cnt from A) - (select count(*) cnt from B)) <0
THEN ((select count(*) cnt from A) - (select count(*) cnt from B))* -1
ELSE ((select count(*) cnt from A) - (select count(*) cnt from B)) END) Difference
FROM dualor this is simpler
SELECT abs(((select count(*) cnt from A) - (select count(*) cnt from B))) difference FROM dualEdited by: Caitanya on Jan 9, 2009 7:12 AM
Applied abs function after seeing BluShadow's post :)

Similar Messages

  • How to compare records in singe internal table

    Hi Folks,
    iam having 3 records in my first itab( T_FINAL) with fields
    material no,  descrip ,  mat type and  group.
    and 16 records in second itab(T_MVKE ) with fields
    mat no ,  distri.chanel  and division
    now I want to fetch the records from T_MVKE  by comparing the records in
    T_FINAL .my requirement is to check the given mat no. in sales org.2000,2100.  if yes then i have to consider 2000 only, if it is in only 2100 then consider 2100 only . is it is in 2000 only then consider 2100 only
    my code is
    LOOP AT T_FINAL.
        READ TABLE T_MVKE WITH KEY MATNR = T_FINAL-MATNR.
       IF SY-SUBRC = 0.
       ON CHANGE OF T_MVKE-MATNR OR T_MVKE-VKORG.
    IF T_MVKE-VKORG = '2000' and SY-TABIX > 1.
          CONCATENATE '2000' 'TS' P_WERKS T_FINAL-MATNR INTO KEY.
    ELSEIF T_MVKE-VKORG = '2000' AND SY-TABIX = 1.
         CONCATENATE '2000' 'TS' P_WERKS T_FINAL-MATNR INTO KEY.
    ELSE.
        CONCATENATE '2100' 'TS' P_WERKS T_FINAL-MATNR INTO KEY.
        ENDIF.
    this logic fails ,. could tell me how to compare values in single itab?
    Thanks
    neha

    Hi ,
    if i've understand you correctly , try that:
    LOOP AT t_final.
      AT NEW matnr.
        CLEAR: v_2000, v_2100.
    *1) 2000
        READ TABLE  t_mvke    WITH KEY matnr = t_final-matnr
                                       vkorg = 2000.
        IF sy-subrc = 0.
          v_2000 = 'X'.
        ENDIF.
    *2) 2100
        READ TABLE  t_mvke    WITH KEY matnr = t_final-matnr
                                       vkorg = 2100.
        IF sy-subrc = 0.
          v_2100 = 'X'.
        ENDIF.
    *compare
        IF v_2000 = 'X' AND  v_2100 = 'X'.
    *read 2000 only
        ELSEIF v_2000 = ' '  AND v_2100 = ' '.
    *nothing found
        ELSE.
    *all other combinations
    *read 2100 only
        ENDIF.
      ENDAT.
    ENDLOOP.
    regards Andreas

  • File to Jdbc: how to get record count from DB table

    Hello,
    i have a scenario file to JDBC....ihave to insert input file data to DB table.
    now my requirement is ..if i insert a file with 50 records to db table on first time, and then next time if i insert the file with 100 records to db table....the count should start from 51 in db table.
    if i insert another file 3rd time, with 25 records, the count shold start from 151...so how can i achieve this functionality....
    i think following options:
    1. in mapping write lookup to call JDBC sender channel and fetch count and map same to target filed of DB. if this is ok...please provide UDF code..2. db triggers (not suitable for my req.)
    So kindly let meknow possible solutions and required UDF codes..please
    Thanks in advance...SARAN

    >>>..if i insert a file with 50 records to db table on first time, and then next time if i insert the file with 100 records to db table....the count should start from 51 in db table.
    if i insert another file 3rd time, with 25 records, the count shold start from 151...so how can i achieve this functionality....
    i think following options:
    Suggestions:
    1)Create an id column in db table.  Talk to DB guy to create oracle sequencer for that column. So, every time you insert record that field will be updated with oracle sequencer. You dont need to handle this.
    Refer this link
    http://www.techonthenet.com/oracle/sequences.php
    2) If you want to handle via pi,  following suggestions..
    If you use PI 7.1 or above, use jdbc lookup in the mapping and do the query  something like this
    Refer this link
    /people/jin.shin/blog/2008/02/15/sap-pi-71-mapping-enhancements-series-graphical-support-for-jdbc-and-rfc-lookups
    Do select query as below
    select count(*) from tablename;
    the above query will return number of rows exist in the table. So use that value and map it in the target field.
    If you use pi 7.0 or below then use the previous reply and do the UDF implementation for jdbc lookup during mapping. Because jdbc lookup does not support in those versions.
    Hope that helps.
    Baskar

  • How to compare records in the same table?

    I have a table of course registrations.  I would like to select course registrations as of a certain date that do not have a dropped status against it.
    CREATE TABLE REGISTRATIONS
    (ID VARCHAR(7) ,
    COURSE VARCHAR(4),
    CURRENT_STATUS VARCHAR(10),
    STATUS_DATE VARCHAR(10))
    INSERT INTO REGISTRATIONS
    (ID, COURSE, CURRENT_STATUS, STATUS_DATE)
    VALUES
    ('1111111','ADMN', 'REGISTERED', '2014-04-10'),
    ('1111111','MATH', 'REGISTERED', '2014-04-10'),
    ('1111111','ADMN', 'DROPPED', '2014-04-10'),
    ('1111111','MATH', 'DROPPED', '2014-04-12'),
    ('1111111','BIOL', 'REGISTERED', '2014-04-10')
    SELECT * FROM REGISTRATIONS
    ORDER BY COURSE, CURRENT_STATUS
    drop table REGISTRATIONS
    ID COURSE CURRENT_STATUS STATUS_DATE
    1111111 ADMN DROPPED 2014-04-10
    1111111 ADMN REGISTERED 2014-04-10
    1111111 BIOL REGISTERED 2014-04-10
    1111111 MATH DROPPED 2014-04-12
    1111111 MATH REGISTERED 2014-04-10
    The above example shows that ID '1111111' has registered for ADMN and BIOL on April 10th but dropped ADMN the same day.  It also shows that they registered for MATH on April 10th but dropped it on the 12th.
    If I were to select course registrations to date as of April 10 I would see both ADMN records, BIOL and MATH.  BIOL and MATH would be OK but I don't want to see the ADMN data in the result because they have essentially cancelled themselves out. 
    In saying that, how do I write a script to select all course registrations as of a certain date but omit the ones that have been dropped at anytime before the select date?

    check below,
    SELECT * FROM REGISTRATIONS a
    WHERE CURRENT_STATUS <> 'DROPPED' AND STATUS_DATE <= '2014-04-12'
    AND COURSE NOT IN (
    SELECT COURSE FROM REGISTRATIONS
    WHERE CURRENT_STATUS = 'DROPPED' AND STATUS_DATE <= '2014-04-12')
    ORDER BY a.COURSE, a.CURRENT_STATUS

  • How to compare the contents of two different tables

    hello. can somebody give me an idean on how to compare the contents of two different tables in mysql?
    example, i have a table named Main List and a table named New List.
    The contents of the New List should be compared to the contents of the
    Main List, to check if they are equal. I don't have any idea how to manipulate
    this data. Hoping for your help. Thanks.

    it is better to comapre it using java.. try get the resultset first and store that in collections then comapre the two collections

  • How can I make my query to compare only columns of two tables... not the storage information?

    11GR2
    =-----------------------------------
    I am using below querry to compare two table that has same name, under two different users... But after making storage information false like below and  if the storage information is different on column level than it create "Alter modify " statements for the column ... How can I make my query to compare only columns of two tables... not the storage information?
    begin
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'PRETTY', TRUE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SQLTERMINATOR',TRUE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SEGMENT_ATTRIBUTES', FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE', FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'TABLESPACE',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'CONSTRAINTS',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'REF_CONSTRAINTS',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'CONSTRAINTS_AS_ALTER',FALSE);
    End;
    select REGEXP_REPLACE(dbms_metadata_diff.compare_alter('TABLE','TABLE_NAME_A','TABLE_NAME_A','USER1','USER2'),('USER1...'),'', 1, 0, 'i') from dual

    I am using below querry to compare two table that has same name, under two different users... But after making storage information false like below and  if the storage information is different on column level than it create "Alter modify " statements for the column ... How can I make my query to compare only columns of two tables... not the storage information?
    If you want help you have to SHOW us what you are doing and how you are doing it; you can't just try to tell us in your own words.
    We can't see your computer screen.

  • How to find the unmatched records between the two tables?

    We have to tables in SQL Server database.
    But unable to find the unmatched record betwwen these two tables.
    There 12 records are unmatched. But unable to get those records.
    I am using the below sql:
    select c1,c2,c3,c4,c5,c6 from Table1
    except select c1,c2,c3,c4,c5,c6 from Table2
    Please help. Thanks in advance.

    Hi knra,
    Please try the following codes:
    select c1,c2,c3,c4,c5,c6 from Table1 t1
    where not exists
    (select * from Table2 t2
    where t1.c1= t2.c1
    and t1.c2= t2.c2
    and t1.c3= t2.c3
    and t1.c4= t2.c4
    and t1.c5= t2.c5
    and t1.c6= t2.c6)
    Best Regards,
    Allen Li
    Allen Li
    TechNet Community Support
    This is what I would've said, but it would make life much easier for you if you have a reference or ID for each entry, this is why we use keys.

  • How to display records into a non table base block..

    Hi,
    Can anybody help me how to display records into a non table base block....
    Find below is my coding but it only display the last record in the first line
    in the block.
    PROCEDURE CREATE_CARTON_QUESTION IS
    CURSOR car_c IS
    select /*+ rule */ question_id, question_description
    from WHOP.QADB_QUESTIONS
    where question_category = 'Carton'
    and question_active_flag = 'Y';
    v_found VARCHAR2(10);
    v_status boolean;
    v_error      varchar2(150);
    v_count number;
    car_r car_c%rowtype;
    begin
    begin
    select count(*) into v_count
    from WHOP.QADB_QUESTIONS
    where question_category = 'Carton'
    and question_active_flag = 'Y';
         exception
         when no_data_found then
         v_count := 0;
    end;
    if v_count > 0 then
    for car_r in car_c loop
    ---populating carton questions
    :la_carton.carton_question_id     := car_r.question_id;
    :la_carton.carton_question_answer     := 'N';
    :la_carton.carton_error_details     := null;
    :la_carton.attribute2          := car_r.question_description;
    end loop;
    end if;
    end;
    Thanks in advance.
    Regards,
    Jun

    Hi SNatapov,
    Thanks for you reply but still I get this error...
    FRM-40737 Illegal restricted procedure GO_BLOCK in WHEN-VALIDATE-ITEM trigger.
    Please note that I call that program unit in the last field of my control block inside when-validate-item trigger the questions should be display in la_carton block which is my non-base table block.
    Find below is the code....
    begin
    go_block('la_carton');
    first_record;
    for car_r in car_c loop
    ---populating carton questions
    :la_carton.carton_question_id := car_r.question_id;
    :la_carton.carton_question_answer := 'N';
    :la_carton.carton_error_details := null;
    :la_carton.attribute2 := car_r.question_description;
    next_record;
    end loop;
    end;
    Hoping you can help me this problem...
    Thanks in advance.
    Regards,
    Jun

  • Get records count of all tables

    Hi ,
    I am trying to get the record count of all tables using dynamic query. I don't know how to put the value in placeholder. I tried the below code.
    SET SERVEROUTPUT ON SIZE 1000000
    DECLARE
         CURSOR table_list
         IS
         select OBJECT_NAME from user_objects
         where object_type in ('TABLE')
         and object_name not like '%AUDIT_DDL%'
         AND object_name not like 'MD_%'
         AND object_name not like 'EXT_%'
         AND object_name not like 'STG_%'
         AND object_name not like 'SYS_%'
         AND object_name not like 'TMP_%'
         AND object_name not like 'TEMP_%'
         order by 1;
         v_count     NUMBER :=0;
         query_str VARCHAR2(1000);
    BEGIN
         FOR table_name IN table_list
         LOOP
              query_str :='SELECT COUNT(1) FROM  ' || table_name.OBJECT_NAME;
    dbms_output.put_line(query_str);
              dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME );
              v_count:= execute immediate query_str;
              dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME || ', Count ' || v_count );
         END LOOP;
    END;
    I know I am doing wrong in the bold lines. But not sure how to fix it. Please help. Thanks in advance.

    Hi,
    Welcome to the forum!
    What you posted is basically right, assuming you really want to do dynamic SQL t all.
    The only problem with
    961618 wrote:
              query_str :='SELECT COUNT(1) FROM  ' || table_name.OBJECT_NAME; would be if the object name included special characters (such as single-quotes) or lower-case letters. To avoid any possible problems, I would put the object name inside double-quotes:
    ...     query_str := 'SELECT COUNT (*) FROM "' || table_name.OBJECT_NAME
                                               || '"';
              v_count:= execute immediate query_str;
    The correct syntax is
    execute immediate query_str INTO v_count;V_count will be the number of rows in a single table. Keep another variable (say total_v_count) that keeps the total count so far.
    Do you really need dynamic SQL?
    SELECT     SUM (num_rows)     AS total_rows
    FROM     user_tables
    WHERE     table_name     NOT_LIKE '%AUDIT_DDL%
    AND     ...
    ;gets the same information, accurate as of the last time statistics were gathered, and some of the numbers may be approximate. Depending on how you use the results, that may be good enough for you. If you actually have 10,000,123 rows, and the query says you have 10,000,000, does it really matter?

  • How to delete records from dynamic internal table.

    Hi Experts,
    Need urgent help!!!
    Issue is with Dynamic internal tables.
    Below is code written by me :
    FORM select_query USING Lw_tabnam
                      TYPE  t682i-kotabnr.
      DATA :  lw_line  TYPE REF TO data,
              lw_line1 TYPE REF TO data.
        CREATE DATA Lw_line    TYPE (lw_TABNAM).
        ASSIGN      Lw_line->* TO   <WA_tbl>.
        CREATE DATA LW_LINE    TYPE STANDARD TABLE OF (Lw_tabnam)
                               WITH NON-UNIQUE DEFAULT KEY.
        ASSIGN      Lw_line->* TO <TBL>.
        SELECT * FROM  (Lw_tabnam)
                 INTO CORRESPONDING FIELDS OF TABLE <TBL>
                 WHERE (t_keys).
    Endform.
    code is working fine.
    here even the table name and where condition are dynamic,everything is fine upto this point.
    Now i have to delete some record from <TBL> based on some conditons.
         for ex : ( here lc_fieldname is KUNNR)
          loop at t_kunnr.
              lw_tabix = sy-tabix.
            Read table <tbl>
                    with key (lc_fieldname) = t_kunnr-kunnr ASSIGNING <wa_tbl>.
            If sy-subrc = 0.
            *Delete
            delete <tbl> from <wa_tbl>
    delete <tbl> index  lw_tabix.
            Endif.
         Endloop.
    The above delete statement doesn't work ,even we can't use index as it gives a syntax error " something related to "index is not allowed in standard table or hash table.
    Can you help me ab't how to delete records in Dynamic internal table?
    Other option that i am thinking of is to create a static table of type dynamic table.
    means, data itab type standard table of <tbl> .I know the syntax is wrong ,however is there any way to do this?
    Thanks in advance ,
    If you have any suggestion ab't this then do let me know.
    bye,
    Gaurav.

    Hi
    I wrote this code and it works fine:
    DATA LW_TABNAM(10) VALUE 'LFA1'.
    DATA : LW_LINES TYPE REF TO DATA,
           LW_LINE  TYPE REF TO DATA.
    FIELD-SYMBOLS: <TABLE> TYPE TABLE,
                   <WA>    TYPE ANY.
    CREATE DATA LW_LINES TYPE TABLE OF (LW_TABNAM)
    WITH NON-UNIQUE DEFAULT KEY.
    ASSIGN LW_LINES->* TO <TABLE>.
    CREATE DATA LW_LINE TYPE (LW_TABNAM).
    ASSIGN LW_LINE->* TO <WA>.
    DO 10 TIMES.
      APPEND INITIAL LINE TO <TABLE>.
    ENDDO.
    SY-TABIX = 4.
    DELETE <TABLE> INDEX SY-TABIX.
    WRITE SY-SUBRC.
    I hope it help you
    Max

  • How to search records in a standard table with * ?

    Hi everyone,
    Can anyone tell me how to search records in a standard table with * ?
    That is, in screen if user type * abc * for searching the records in which the field MC_STEXT contains 'abc'. What the code should be? How to complete the code below?
      SELECT SINGLE objid FROM p1000  INTO p1000-objid,
      WHERE MC_STEXT = ? .
    Thanks!

    Hi
    There are several way to do that, probably just as some guys wrote the easier way is to use LIKE in WHERE condition and the sign % instead of *:
    V_STRING = '%ABC%'.
    SELECT SINGLE objid FROM p1000 INTO p1000-objid,
    WHERE MC_STEXT LIKE V_STRING.
    U can also use a range (just like select-options):
    RANGES: R_MC FOR P1000-MC_STEXT.
    R_MC-LOW = 'ABC'.
    R_MC(3) = 'ICP'.
    APPEND R_MC.
    SELECT SINGLE objid FROM p1000 INTO p1000-objid,
    WHERE MC_STEXT IN R_MC.
    Max

  • How to compare the programs in two different systems

    Hi,
    I have two systems say A & B and i have the program say 'Z_TESTPROG'.
    How to compare the program in two different systems.
    Regards,
    Venkat

    Hi,
    Check the version in Utilities -> version -> version management in both servers is one option.
    Another one is using SE39 transaction.
    Regards
    Manasa

  • Generate delta records by comparing multiple fields from two tables?

    I have two tables with similar fields. Let's say Table 1 (T1) has fields Customer, A, B and C. Table 2 (T2) has fields Customer0002, A0002, B0002 and C0002. For each customer (each record) I want to check whether there is any difference in field A and A0002 or B and B0002 or C and C0002. If there is a difference between any of these pairs of fields then I will update that customer's record. Currently I have a piece of code
       DATA: ls_source TYPE y_source_fields,
            ls_target TYPE y_target_fields.
      LOOP AT it_source INTO ls_source.
        if not ( ls_source-A = ls_source-A0002 ).
          MOVE-CORRESPONDING ls_source TO ls_target.
          APPEND ls_target TO et_target.
        endif.
      ENDLOOP.
    This checks for the difference between one pair - A and A0002. How can I make it check 3 pairs and update when any of them have differences?

    Hello Khaled
    Why don't you add  B and B0002 - C and C0002 fields into your if declaration?
    LOOP AT it_source INTO ls_source.
        if not (
    ls_source-A = ls_source-A0002 and
    ls_source-B = ls_source-B0002 and
    ls_source-C = ls_source-C0002
          MOVE-CORRESPONDING ls_source TO ls_target.
          APPEND ls_target TO et_target.
        endif.
      ENDLOOP.
    I think you have more than 3 fields and the count of these fields are dynamic right?
    Do you about the ASSIGN COMPONENT x OF STRUCTURE y TO <field_symbol>.  usage?
    Can you explain your need in detail please.
    Edited by: Bulent Balci on Jul 27, 2010 4:18 PM

  • How to avoid Duplicate Records  while joining two tables

    Hi,
    I am trying to join three tables, basically two tables are same one is like history table, so I wrote a query like
    select
    e.id,
    e.seqNo,
    e.name,
    d.resDate,
    d.details
    from employees e,
    ((select * from dept)union(select * from dept_hist)) d
    join on d.id=e.id and e.seqno=d.seqno
    but this returing duplicate records.
    Could anyone please tell me how to avoid duplicate records of this query.

    Actually it is like if the record is processed it will be moved to hist table, so both table will not have same records and I need the record from both the tables so i have done the union of both the tables, so d will have the union of both records.
    But I am getting duplicate records if even I am distinct.

  • How to Compare Data length of staging table with base table definition

    Hi,
    I've two tables :staging table and base table.
    I'm getting data from flatfiles into staging table, as per requirement structure of staging table and base table(length of each and every column in staging table is 25% more to dump data without any errors) are different for ex :if we've city column with varchar length 40 in staging table it has 25 in base table.Once data is dumped into staging table I want to compare actual data length of each and every column in staging table with definition of base table(data_length for each and every column from all_tab_columns) and if any column differs length I need to update the corresponding row in staging table which also has a flag called err_length.
    so for this I'm using cursor c1 is select length(a.id),length(a.name)... from staging_table;
    cursor c2(name varchar2) is select data_length from all_tab_columns where table_name='BASE_TABLE' and column_name=name;
    But we're getting data atonce in first query whereas in second cursor I need to get each and every column and then compare with first ?
    Can anyone tell me how to get desired results?
    Thanks,
    Mahender.

    This is a shot in the dark but, take a look at this example below:
    SQL> DROP TABLE STAGING;
    Table dropped.
    SQL> DROP TABLE BASE;
    Table dropped.
    SQL> CREATE TABLE STAGING
      2  (
      3          ID              NUMBER
      4  ,       A               VARCHAR2(40)
      5  ,       B               VARCHAR2(40)
      6  ,       ERR_LENGTH      VARCHAR2(1)
      7  );
    Table created.
    SQL> CREATE TABLE BASE
      2  (
      3          ID      NUMBER
      4  ,       A       VARCHAR2(25)
      5  ,       B       VARCHAR2(25)
      6  );
    Table created.
    SQL> INSERT INTO STAGING VALUES (1,RPAD('X',26,'X'),RPAD('X',25,'X'),NULL);
    1 row created.
    SQL> INSERT INTO STAGING VALUES (2,RPAD('X',25,'X'),RPAD('X',26,'X'),NULL);
    1 row created.
    SQL> INSERT INTO STAGING VALUES (3,RPAD('X',25,'X'),RPAD('X',25,'X'),NULL);
    1 row created.
    SQL> COMMIT;
    Commit complete.
    SQL> SELECT * FROM STAGING;
            ID A                                        B                                        E
             1 XXXXXXXXXXXXXXXXXXXXXXXXXX               XXXXXXXXXXXXXXXXXXXXXXXXX
             2 XXXXXXXXXXXXXXXXXXXXXXXXX                XXXXXXXXXXXXXXXXXXXXXXXXXX
             3 XXXXXXXXXXXXXXXXXXXXXXXXX                XXXXXXXXXXXXXXXXXXXXXXXXX
    SQL> UPDATE  STAGING ST
      2  SET     ERR_LENGTH = 'Y'
      3  WHERE   EXISTS
      4          (
      5                  WITH    columns_in_staging AS
      6                  (
      7                          /* Retrieve all the columns names for the staging table with the exception of the primary key column
      8                           * and order them alphabetically.
      9                           */
    10                          SELECT  COLUMN_NAME
    11                          ,       ROW_NUMBER() OVER (ORDER BY COLUMN_NAME) RN
    12                          FROM    ALL_TAB_COLUMNS
    13                          WHERE   TABLE_NAME='STAGING'
    14                          AND     COLUMN_NAME != 'ID'
    15                          ORDER BY 1
    16                  ),      staging_unpivot AS
    17                  (
    18                          /* Using the columns_in_staging above UNPIVOT the result set so you get a record for each COLUMN value
    19                           * for each record. The DECODE performs the unpivot and it works if the decode specifies the columns
    20                           * in the same order as the ROW_NUMBER() function in columns_in_staging
    21                           */
    22                          SELECT  ID
    23                          ,       COLUMN_NAME
    24                          ,       DECODE
    25                                  (
    26                                          RN
    27                                  ,       1,A
    28                                  ,       2,B
    29                                  )  AS VAL
    30                          FROM            STAGING
    31                          CROSS JOIN      COLUMNS_IN_STAGING
    32                  )
    33                  /*      Only return IDs for records that have at least one column value that exceeds the length. */
    34                  SELECT  ID
    35                  FROM
    36                  (
    37                          /* Join the unpivoted staging table to the ALL_TAB_COLUMNS table on the column names. Here we perform
    38                           * the check to see if there are any differences in the length if so set a flag.
    39                           */
    40                          SELECT  STAGING_UNPIVOT.ID
    41                          ,       (CASE WHEN ATC.DATA_LENGTH < LENGTH(STAGING_UNPIVOT.VAL) THEN 'Y' END) AS ERR_LENGTH_A
    42                          ,       (CASE WHEN ATC.DATA_LENGTH < LENGTH(STAGING_UNPIVOT.VAL) THEN 'Y' END) AS ERR_LENGTH_B
    43                          FROM    STAGING_UNPIVOT
    44                          JOIN    ALL_TAB_COLUMNS ATC     ON ATC.COLUMN_NAME = STAGING_UNPIVOT.COLUMN_NAME
    45                          WHERE   ATC.TABLE_NAME='BASE'
    46                  )       A
    47                  WHERE   COALESCE(ERR_LENGTH_A,ERR_LENGTH_B) IS NOT NULL
    48                  AND     ST.ID = A.ID
    49          )
    50  /
    2 rows updated.
    SQL> SELECT * FROM STAGING;
            ID A                                        B                                        E
             1 XXXXXXXXXXXXXXXXXXXXXXXXXX               XXXXXXXXXXXXXXXXXXXXXXXXX                Y
             2 XXXXXXXXXXXXXXXXXXXXXXXXX                XXXXXXXXXXXXXXXXXXXXXXXXXX               Y
             3 XXXXXXXXXXXXXXXXXXXXXXXXX                XXXXXXXXXXXXXXXXXXXXXXXXXHopefully the comments make sense. If you have any questions please let me know.
    This assumes the column names are the same between the staging and base tables. In addition as you add more columns to this table you'll have to add more CASE statements to check the length and update the COALESCE check as necessary.
    Thanks!

Maybe you are looking for

  • HP OfficeJet Pro L7680 - New ink cartridges saying "Empty"

    I have a HP OfficeJet Pro L7680 that has two ink cartridges that suggest they are empty, although they are brand new from HP. These are replacement carts, not the original. I am not sure how to diagnose the problem since the cartridges are leaking co

  • Unable to export from Crystal Report - font OCR A STD

    We currently  have Crystal Report version 11.5, but I am having the issue of not being able to export the Crystal report file to PDF due to the report has font OCR A STD.  Error message is 'Failed to Export Report.'  Are there any options to resolve

  • Need help with something...

    Hey guys, need some help with this, try to keep up with me here... I opened up illustrator cs4 and drew individual items (three items) and drew all three on one artboard and saved it as a standard .AI file. On each of the three items, one at a time I

  • Some books in iBooks won't open after iOS 8.1.3

    I have an iPad Air and today I just updated to iOS 8.1.3. When I go to open ebooks or pdfs in iBooks, only certain books will open. When I press on the icon after about 10 seconds a little the sunburst icon in the middle appears, cycles through and t

  • How to change color inside single item? [SOLVED]

    I'd like to change background color inside item (on blue for ex.: see http://www.marussig.si/weblib/screen.jpg ) . The problem is that the block is multiline block but I have to change the color just on one line in one column. Is this possible? If I