SQL表数据比较

时间:2014-09-25 09:51:33

标签: sql sql-server join union

我需要比较两个表行,并且只显示具有不同数据的coulmns,即来自两个表的不匹配数据。假设Table1和Table2具有50列,并且只有错误记录是5然后coulms需要进入Select语句

Comparsion部分用Union查询完成,我的障碍是如何得出错误的行列名。

2 个答案:

答案 0 :(得分:0)

一种方法是在一个字符串中连接所有这些列名的列表:

select
T1.id, case when t1.col1<> t2.col1 then 'Col1;' else '' end +
    case when t1.col2<> t2.col2 then 'Col2;' else '' end 
    -- similar case statementes for all th columns you want to be included 
    -- in the list
    as Mismatchedcolumns
from Table1 T1
Join Table2 T2 on T1.id = T2.id

Check Demo here..

答案 1 :(得分:0)

如果您正在查看所有不匹配列的列表,请参阅下面的示例

CREATE TABLE TableA
    ([Product] varchar(1), [Qty] int, [Price] int, [Comments] varchar(3))
;

INSERT INTO TableA
    ([Product], [Qty], [Price], [Comments])
VALUES
    ('A', 20, 500, 'xyz'),
    ('B', 50, 200, 'xyz'),
    ('C', 90, 100, 'abc'),
    ('D', 50, 500, 'xyz')
;

CREATE TABLE TableB
    ([Product] varchar(1), [Qty] int, [Price] int, [Comments] varchar(3))
;

INSERT INTO TableB
    ([Product], [Qty], [Price], [Comments])
VALUES

    ('B', 70, 200, 'cv'),
    ('C', 90, 200, 'wsd'),
    ('D', 40, 400, 'xyz'),
    ('E', 50, 500, 'xyz')
;



SELECT  b.Product,
        b.Qty,
        b.Price,
        Result = CASE WHEN a.product IS NULL THEN 'New'
                    ELSE 'Updated: ' + 
                        STUFF(  CASE WHEN a.Qty != b.Qty THEN ',Qty' ELSE '' END + 
                                CASE WHEN a.Price != b.Price THEN ',Price' ELSE '' END,
                            1, 1, '')
                END
FROM    TableB b    
        LEFT JOIN TableA a
            ON a.Product = b.Product
WHERE   a.Product IS NULL
OR      a.Qty != b.Qty
OR      a.Price != b.Price

union

SELECT 
a.Product,a.Qty,a.Price, 'NewA' as Result
FROM 
TABLEA a left join
TABLEB b on a.Product = b.Product
WHERE b.Product is null

SQL Server 2008 compare two tables in same database and get column is changed

的解决方案的修改版本

http://sqlfiddle.com/#!3/d1b3f/3