Find Differences between two tables at column level

Hi,
I have 2 tables one live table and the other History table..
If i have to find differences between live table and the latest version in the History table and also find which column got chaanged
How would i do that for a table which has many columns and i need each column for which the value has changed for a id
for ex:
  Table 1   (LIve)                           Table 2 (History)
ID col1     col2    Version               ID       col1     col2    Version
 1   ABC     123     V1                     1       ABCD   123     v2
 2   NBS     1234   V1                     2        NBS     123     V2
Result set should be 
Result Set:
ID col which changed
1    col1
2    col2   
Because the values for that column had been changed
Except gives me all the differences not just the column level ..

The dynamic version using schema views... :D
--Build a coulple OF testing tables to play with
CREATE TABLE dbo.Table1 (
ID INT IDENTITY(1,1) PRIMARY KEY,
Col1 INT,
Col2 INT,
Col3 INT
CREATE TABLE dbo.Table2 (
ID INT IDENTITY(1,1) PRIMARY KEY,
Col1 INT,
Col2 INT,
Col3 INT
INSERT dbo.Table1 (Col1,Col2,Col3) VALUES
(123,456,789),
(111,222,333),
(444,555,666),
(777,888,999),
(321,345,769),
(179,753,758),
(362,362,236),
(856,874,896),
(821,729,324)
INSERT dbo.Table2 (Col1,Col2,Col3) VALUES
(123,456,789),
(111,999,333), --col2 diff
(444,555,666),
(777,888,999),
(321,345,123), --col3 diff
(179,753,758),
(362,362,236),
(234,874,896), --col1 diff
(821,729,324)
And then the actual solution...
DECLARE
@t1 VARCHAR(10) = 'Table1',
@t2 VARCHAR(10) = 'Table2'
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
SELECT
c.TABLE_SCHEMA,
c.TABLE_NAME,
c.COLUMN_NAME,
c.ORDINAL_POSITION,
CASE WHEN u.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS PK
INTO #temp
FROM
INFORMATION_SCHEMA.COLUMNS c
JOIN INFORMATION_SCHEMA.TABLES t
ON c.TABLE_NAME = t.TABLE_NAME
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE u
ON c.COLUMN_NAME = u.COLUMN_NAME
AND c.TABLE_NAME = u.TABLE_NAME
AND c.TABLE_SCHEMA = u.TABLE_SCHEMA
AND OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
WHERE 1 = 1
AND t.TABLE_TYPE = 'BASE TABLE'
AND c.TABLE_NAME IN (@t1,@t2)
ORDER BY
c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION
DECLARE @select VARCHAR(MAX)
SELECT @select = COALESCE(@select + ', ', '') + t.TABLE_SCHEMA + '.' + t.TABLE_NAME + '.' + t.COLUMN_NAME
FROM #temp AS t
ORDER BY t.TABLE_NAME, t.ORDINAL_POSITION
DECLARE @from VARCHAR(MAX)
SELECT @from = COALESCE(@from + ' FULL JOIN ', '') + t.TABLE_SCHEMA + '.' + t.TABLE_NAME
FROM #temp AS t
WHERE t.PK = 1
ORDER BY t.TABLE_NAME
DECLARE @on VARCHAR(MAX)
SELECT @on = COALESCE(@on + ' = ', '') + t.TABLE_SCHEMA + '.' + t.TABLE_NAME + '.' + t.COLUMN_NAME
FROM #temp AS t
WHERE t.PK = 1
ORDER BY t.TABLE_NAME, t.ORDINAL_POSITION
DECLARE @where VARCHAR(MAX)
SELECT @where = COALESCE(@where + CASE WHEN t.TABLE_NAME = @t1 THEN ' OR ' ELSE ' <> ' END, '') + t.TABLE_SCHEMA + '.' + t.TABLE_NAME + '.' + t.COLUMN_NAME
FROM #temp AS t
WHERE t.PK = 0
ORDER BY t.ORDINAL_POSITION, t.TABLE_NAME
DECLARE @sql VARCHAR(MAX) = '
SELECT ' + @select + '
FROM ' + @from + '
ON ' + @on + '
WHERE ' + @where
EXEC (@sql)
HTH,
Jason

Similar Messages

  • Need to find the Difference between two table

    Hello ,
    I have stucked in program as below scenario:-
    I have two tables of huge data of same structure in a same schema.I need to find the difference exact values in tables.
    By using MINUS we can find the difference between two table ,i need to find the what exact difference in the there values with colunm and value at that column.
    Example TableA
    Col1 col2 col3 col4 col5.... col50
    10 ABC 2001 EE 444 TT
    40 XYZ 3002 RR 445 TT3
    80 DEF 6005 YY 446 YY8
    TableB
    Col1 col2 col3 col4 col5.... col50
    10 ABC 2001 EE 444 TT
    40 XYZ 3002 RR 445 TT3
    81 DEF 6005 Yu 447 YY8
    I need to the out put like this :-
    The Diffence between two table is
    TableA.COL1=80 TableB.Col1=81, Different
    TableA.Col4=YY TableB.col4=Yu,Different
    TableA.Col5=446TableB.col5=447,Different
    Please suggest me to write the pl/sql program for the same
    thanx in advance
    KK

    Thanx friends for all your efforts
    I have a sample code for the same,this will compare the two tables for single row in each table .
    what r the modification needed for the multiple rows of values in the two tables??
    Please suggest!!
    CREATE OR REPLACE PROCEDURE test_compare
    IS
    TYPE t_col
    IS
    TABLE OF VARCHAR2 (30)
    INDEX BY PLS_INTEGER;
    l_col t_col;
    j NUMBER := 0;
    l_sql VARCHAR2 (2000);
    col1 VARCHAR2 (30);
    col2 VARCHAR2 (30);
    val1 NUMBER;
    val2 NUMBER;
    status VARCHAR2 (30);
    CURSOR c1
    IS
    SELECT column_id, column_name
    FROM all_tab_columns
    WHERE table_name = 'TEST1';
    BEGIN
    FOR i IN c1
    LOOP
    j := j + 1;
    l_col (j) := i.column_name;
    END LOOP;
    FOR k IN 1 .. j
    LOOP
    l_sql :=
    'SELECT '
    || ''''
    || l_col (k)
    || ''''
    || ', '
    || 'TEST2.'
    || l_col (k)
    || ', '
    || ''''
    || l_col (k)
    || ''''
    || ', '
    || 'TEST1.'
    || l_col (k )
    || ', '
    || 'DECODE(TEST2.'
    || l_col (k)
    || ' -TEST1.'
    || l_col (k)
    || ', 0, ''NO CHANGE'', ''CHANGED'') FROM TEST2, TEST1';
    EXECUTE IMMEDIATE l_sql INTO col1, val1,col2, val2, status;
    IF status = 'CHANGED'
    THEN
    DBMS_OUTPUT.put_line( 'TEST2.'
    || col1
    || '='
    || val1
    || ', TEST1.'
    || col2
    || '='
    || val2
    || ', '
    || status);
    END IF;
    END LOOP;
    EXCEPTION
    WHEN OTHERS
    THEN
    DBMS_OUTPUT.put_line ('Error:- ' || SQLERRM);
    END;
    /

  • How to find the structural difference between two tables

    Hi all,
    How to find the structural difference between two tables .
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE 11.1.0.7.0 Production
    TNS for 32-bit Windows: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - Production
    Thanks,
    P Prakash

    you could try something similar to this, for each table pair that you want to compare:
    SELECT 'TABLE_A has these columns that are not in TABLE_B', DIFF.*
      FROM (
            SELECT  COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_A'
             MINUS
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_B'
          ) DIFF
    UNION
    SELECT 'TABLE_B has these columns that are not in TABLE_A', DIFF.*
      FROM (
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_B'
             MINUS
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_A'
          ) DIFF;that's assuming, column_name, data_type and data_length are all you want to compare on.

  • Bestway to find difference between two roles in quality and production

    We have a process of collecting su53 dump and then analyze for missing authorization . However some time although everything works fine in quality , it fails in production . Hence I want to know a simple methodology to compare roles in quality and production to know difference ... Can anyone share best methodolgy being used in your setup ?
    NPB

    (1)How to find the difference between two dates at Universe level and at report Level in IDT?
    DaysBetween ([Sale Date];[Invoice Date]) returns 2 if [Sale Date] is 15 December 2001 and [Invoice Date] is 17 December 2001.
    (2) How to change format of dates from YYYY/MM/DD to DD/MM/YYYY in IDT at prompt level ?
    =FormatDate(ToDate(YOUR DARE OBJECT);"YYYY/MM/DD");"dd'/'MM'/'yyyy")
    =To_Char (object name, required format)
    Find the below link for more info.
    http://scn.sap.com/community/semantic-layer/blog/2014/04/18/bi41-business-layer-enhancements--create-display-format
    (3)What is VIEWS in IDT of data foundation layer when we right click? could u plz give one example where exactly we use VIEWS?
    A custom data foundation view is a subset of the data foundation Master view. You can use views when editing a large data foundation, and interested in working with a subset of tables. You can define multiple custom views for the data foundation due to the complexity of the data warehouse.
    Essentially, need created views for each individual star scheme (like Sales, Production, Finance, Accounting, etc.) plus a view for eachcomplex dimension structure (like Business Partner, Material, Customer, Plant etc.),
    Find the below link for more info.
    http://scn.sap.com/docs/DOC-54422
    (4) How to represent & report my IDT data in dashboards? could u plz explain the steps?
    Please find the below link: http://scn.sap.com/docs/DOC-27559

  • How to find differences between two columns

    Hello I need the formula to spot differences between two columns and to write on a third one if the same name appear on the two columns.
    For example:
    rome berlin true
    berlin moscow false
    chicago toronto true
    toronto chicago true
    florence
    Thanks
    Lorenzo

    You should be able to use COUNTIF where the range is th first column and the condition is the word in the second column. If the result is greater than zero then the word is in both columns.

  • To find difference between two dates

    Hi all,
    I am new to this forum and oracle.
    I want to get the difference between two dates. My query is as below...
    sqlserver_utilities.datediff('YY', startdate,enddate)
    I want the difference in year.
    Please help me. It's really urgent.
    Thanks in advance.
    Regards,
    Inam

    Select to_char(enddate,'YY') - to_char(startdate,'YY') fromPLEASE don't do that. There are so many things wrong with it...
    for example:
    1). Why are you subtracting character data types?
    2). What if the start date is 1999 and the end date is 2000? Do you expect to get a difference of -1?
    3). What if the start date is 1 Jan 2000 and the end date is 31 Dec 2000? Do you expect to get 0 instead of 1 or .997?
    4). Why would you convert dates to something else when they are inherently subtractable.
    5). There are obvious points in the OP's "specification" that are vague - the best thing (after telling them to search, of course since this has been answered a million times already) would be to try to clarify the spec.
    John

  • Most elegant way to get difference between two tables - not minus!!!

    Hi,
    Simplified example of what I am trying to achieve - I have two tables ORIGINAL and REVISED.
    My desired result is to compare the two, such that; -
    Where data exists in both tables I get the difference between the Budget column, and if there is no difference then I want no rows.
    Where data exists in ORIGINAL but not in revised I want the inverse of the current value of the Budget column.
    Where data exists in REVISED I want the value from REVISED.
    I can see how I can do this, cf below, but is there a more elegant solution??
    Data for table ORIGINAL
    select '801040' entity, '2186' expense_type, 234000 budget
    from dual
    union all
    select '801040' entity, '3001' expense_type, 1000 budget
    from dual
    union all
    select '801040' entity, 'P132' expense_type, 34000 budget
    from dual
    union all
    select '801040' entity, 'P135' expense_type, 43000 budget
    from dualData for table REVISED
    select '801040' entity, '2186' expense_type, 235000 budget
    from dual
    union all
    select '801040' entity, 'P132' expense_type, 34000 budget
    from dual
    union all
    select '801040' entity, 'P139' expense_type, 56000 budget
    from dualDesired output
    ENTITY EXPENSE_TYPE DIFFERENCE
    801040 2186 1000
    801040 3001 -1000
    801040 P135 -43000
    801040 P139 56000
    5 rows selected.
    Current code to achieve this, is there a better way??
    select original.entity
    ,      original.expense_type
    ,       (nvl(revised.budget,0) - original.budget) as difference
    from   original
    ,      revised
    where  original.entity = revised.entity(+)
    and    original.expense_type = revised.expense_type(+)
    and   (nvl(revised.budget,0) - original.budget) != 0
    union all
    select  revised.entity
    ,       revised.expense_type
    ,       revised.budget as difference
    from   revised
    where  not exists
    (select 'x'
    from   original
    where  original.entity = revised.entity
    and    original.expense_type = revised.expense_type)
    and    revised.budget != 0Many thanks for your input,
    Robert.
    Edited by: Robert Angel on 17-Jan-2012 03:31 to change not equals to != - thanks for heads up

    Use full outer join:
    with original as (
                      select '801040' entity, '2186' expense_type, 234000 budget from dual union all
                      select '801040' entity, '3001' expense_type, 1000 budget from dual union all
                      select '801040' entity, 'P132' expense_type, 34000 budget from dual union all
                      select '801040' entity, 'P135' expense_type, 43000 budget from dual
          revised as (
                      select '801040' entity, '2186' expense_type, 235000 budget from dual union all
                      select '801040' entity, 'P132' expense_type, 34000 budget from dual union all
                      select '801040' entity, 'P139' expense_type, 56000 budget from dual
    select  nvl(o.entity,r.entity) entity,
            nvl(o.expense_type,r.expense_type) expense_type,
            nvl(r.budget,0) - nvl(o.budget,0) budget
      from      original o
            full join
                revised r
              on (
                      r.entity = o.entity
                  and
                      r.expense_type = o.expense_type
      where nvl(r.budget,0) - nvl(o.budget,0) != 0
    ENTITY     EXPE         BUDGET
    801040     2186           1000
    801040     3001          -1000
    801040     P135         -43000
    801040     P139          56000
    SQL> SY.

  • Find difference between two numbers (DBL)

    Hello All,
    Is there a function in labview other than subtraction function that can find the difference between the two given numbers?
    Thanks,
    Davidson
    Solved!
    Go to Solution.

    I think if he wanted to find absolute value he would have mentioned it.
    And not asked about other function for taking difference.
    Do you want to fight over this? When it is mentioned "DIFFERENCE" and not "ABSOLUTE" value.
    Anyways..Will fight tomorrow. I am going home.
    Best of luck
    Gaurav k
    CLD Certified !!!!!
    Do not forget to Mark solution and to give Kudo if problem is solved.

  • Oracle 11g sql to find difference from two table data

    I have two tables ACTUAL AND ESTIMATE having unique column(sal_id, gal_id) and amount, tax, date columns.
    ACTUAL table
    actual_id, sal_id, gal_id, process_flag, amount, tax     date
    A1 101 201 Y 10 1 27-Aug-12
    A2 102 202 Y 20 2 27-Aug-12
    A3 102 202 N 30 3 29-Aug-12
    A4 302 402 N 40 3 30-Aug-12
    ESTIMATE table
    estimate_id, sal_id, gal_id, process_flag, amount, tax  date
    E1 301 401 Y 5 1 19-Aug-12
    E2 302 402 Y 45 4 20-Aug-12
    E3 302 402 Y 50 5 25-Aug-12
    E4 301 403 Y 10 2 27-Aug-12
    E5 301 403 N 15 3 28-Aug-12
    E6 101 201 Y 12 3 29-Aug-12
    Now My FINAL table, 1) Should have record for unprocessed (process_flag='N') from ACTUAL/ESTIMATE table for difference in amount and tax for (sal_id + gal_id) combination. If more than one processed record there, then max (date) should be consider.
    FINAL table
    actual_id, estimate_id, sal_id, gal_id, amount, tax
    A3 null 102 202 10 1 (A3-A2 actual-actual)
    A4 null 302 402 -10 -2 (A4-E3 actual-estimate with max date)
    null E5 301 403 5 1 (E5-E4 estimate-estimate)
    null E6 101 201 2 2 (E6-A1 estimate-actual)
    So basically I need a query for (A-A) U (B-B) U (A-B) U (B-A).
    I am using Oracle 11g Please help me.
    Edited by: Suresh on Aug 31, 2012 7:38 PM
    Edited by: Suresh on Aug 31, 2012 7:38 PM
    Edited by: Suresh on Aug 31, 2012 10:53 PM

    You need to provide better explanation here.A-A is always null.
    You might be looking for something like this..
    Untested version and also i cannot read your mind
    select actual_id, sal_id, gal_id, process_flag,ld_amount,ld_tax,e_date
    from(
    select actual_id, sal_id, gal_id, process_flag,e_date, amount-lead(amount) over(partition by sal_id, gal_id order by e_date desc) ld_amount,
    tax-lead(tax) over(partition by sal_id, gal_id order by e_date desc) ld_tax,
    rank()  over(partition by sal_id, gal_id order by e_date desc)rnk
    from
    (select * from actual a union
    select * from estmt e)
    ) where rnk=1

  • Find Discrepancies between two tables

    Hello Everyone,
    I have two tables payment and delegate, my payment table for some reason have more entries then in delegate table.
    I can do something like , if the records in delegate table don't exsist....and they are in payments table
    SELECT * FROM
    Delegate d, Payment p
    WHERE d.username != p.username
    The usernames in payment table have to be in delegate table...So now if I want to look for discrepancies how should I find that out....
    Tables Records :
    Delegate :
    Username Paid
    User1 Y
    User2 Y
    User3 Y
    User4 Y
    User5 N
    User6 N
    Payment
    username
    User1
    User2
    User3
    User4
    User5
    User6
    So, basically I'm looking that which records are Paid = 'N' and somehow are in payments table:
    In the above example result should be User5 and User6....
    I'm using the old database, so please no fancy queries...even if it takes long time doesn't matter..
    Please advise..
    Thanks,
    Harsimrat
    Message was edited by:
    Harsimrat

    Perfect and if I want to do it other way around....Where there is an entry with Paid = 'y' in delegate table and is not in payments table. How can i find that out ??
    Really appreciate.
    Thanks,
    Harsimrat

  • Find difference between two vectors ?

    Hi,
    I have two vectors, the first contains:
    v1.add("1");
    v1.add("2");
    the second:
    v2.add("1");
    Now I want to print out the difference between both.
    Does anybody have en idea ?
    Regards
    Micha

    Yep, that should definitely do it. I think the point ssav is trying to make is that to solve this problem we need to know your actual requirements. "the difference between" is too vague. Here are some things to think about:
    - Is position important? That is, is a List containing 1 and 2 the same as a List containing 2 and 1 or different?
    - If List A contains 1,2,4,5,6 and List B contains 1,2,3,4,5,6 what would you want to see?
    - What if List A contains 1,2,3 and List B 1,2,2,3?
    - What if List A contains 1,2,3 and Lits B 1,2,and a java.lang.NullPointerException?
    You're probably starting to see that this is not as simple as you thought. Come back with more specific requirements and you may get better help.

  • Help with query to show differences between two tables

    I have two tables that are identically defined. I need to capture changes to the old table. Want a result set that shows the following. I need to know what is new, change, or deleted.  Thanks
    X1,n,new
    z0,n,delete
    z2,y,change
    z3,n,change
    drop table ifs_rmapopold
    create table ifs_rmapopold (rqappl varchar(2), rqcardcurr varchar(1))
    insert into ifs_rmapopold (rqappl, rqcardcurr) values ('z0', 'n'), ('z1', 'n'), ('z2', 'n'), ('z3', 'y')
    drop table ifs_rmapopnew
    create table ifs_rmapopnew (rqappl varchar(2), rqcardcurr varchar(1))
    insert into ifs_rmapopnew (rqappl, rqcardcurr) values ('x1', 'n'),('z1', 'n'), ('z2', 'y'), ('z3', 'n'), ('z4', 'n')

    Got this clumsy example working. But Sorna answer is  really nice.
    create table #temptable (rqappl varchar(2), rqcardcurr varchar(1), updateind varchar(10))
    -- change, get new value
    insert into #temptable
    select n.*, 'change' from ifs_rmapopnew n
    inner join ifs_rmapopold o on n.rqappl = o.rqappl and n.rqcardcurr <> o.rqcardcurr
    -- new
    insert into #temptable
    select n.*, 'new' from ifs_rmapopnew n
    where rqappl not in (select rqappl from ifs_rmapopold)
    -- deleted
    insert into #temptable
    select o.*, 'deleted' from ifs_rmapopold o
    where rqappl not in (select rqappl from ifs_rmapopnew)
    select * from #temptable

  • How to find structural differences between two tables?

    I want to find the difference in structure between objects in two 11g databases:
    Here I want to identify:
    tables/ Views with same columns, same datatype, precision and constraints
    Identify if the same indexes and triggers are present.
    I do not want to compare the data.
    can someone give suggestions on this please?

    my first resource for SQL Developer questions is (That) Jeff Smith: http://www.thatjeffsmith.com/archive/2012/09/sql-developer-database-diff-compare-objects-from-multiple-schemas/.

  • How to find difference in two tables

    Hi all,
    I am having 2 tables (Table1 and Table2 ) same structure.
    1. Table1 is having some data.
    2. Now, i got data in CSV file, which was loaded into Table2.
    This data contains....
    A. Data of Table1
    B. Some colum values are different compare to Table1 column values.
    (Pkey is same, but column values are different in Table1 and Table2)
    C. Additional rows are there compared to Table1.
    Now, what i want is......
    I want to select the data from Table2,
    1. The rows in which column values are different from the Table1
    2. New records added from CSV file (i.e. Those records that are not
    there in Table1).
    Thanks in advance,
    Pal

    Thanks for your solution. It is working, but my problem is
    Table1
    COL1     COL2     COL3     COL4
    1     col2     col3     col4
    2     col2     col3     col4
    3     col2     col3     col4
    4     col2     col3     col4
    Table2
    COL1     COL2     COL3     COL4
    5     col2     col3     col4 -- New row
    6     col2     col3     col4 -- New row
    1     col2     col3     col44 -- Different column value
    2     col2     col3     col4
    3     col2     col33     col4 -- Different column value
    4     col2     col3     col4
    select * from test2
    minus
    select * from test1
    COL1     COL2     COL3     COL4
    1     col2     col3     col44 --- needs to be update
    3     col2     col33     col4 --- needs to be update
    5     col2     col3     col4 --- needs to be insert
    6     col2     col3     col4 --- needs to be insert
    Actually, I need to update and insert those records through LIVE UPDATE in the remote database. In this case, Table1 data is in the remote database. The output of MINUS statement needs to be implimented in Table1, which is in remote database.
    Any suggestion will be appreciated. Thanks,
    Pal

  • Difference between two timestamp.

    Hi,
    I want to find difference between two timestamp in minutes.
    Actually i want to retrieve difference between current timestamp and the timestamp taken from the table
    select log_time from serv_info where server_id = 1;
    Can anyone tell me the query to find difference between two timestamps in minutes.
    -haifriends

    SQL> WITH serv_in AS
         (SELECT SYSTIMESTAMP - 1 / 4 log_time,
                 SYSTIMESTAMP now
            FROM DUAL)
    SELECT log_time,
           now,
             24 * 60 * EXTRACT (DAY FROM (now - log_time))
           + 60 * EXTRACT (HOUR FROM (now - log_time))
           + EXTRACT (MINUTE FROM (now - log_time))
           + 1 / 60 * EXTRACT (SECOND FROM (now - log_time)) diff_in_minutes
      FROM serv_in
    LOG_TIME  NOW                                 DIFF_IN_MINUTES
    01-MRZ-07 01-MAR-07 03.47.42.107462 PM +01:00      360,001791

Maybe you are looking for