SQL Server - Compare 2 tables for data existing in the same columns without checking for equality

≡放荡痞女 提交于 2019-12-11 01:07:31

问题


Update:

Unfortunately, the answer provided here did not give me what I wanted - My mistake for accepting too quickly without really doing a deep enough check.

I have reported the question here.


Suppose I have the following two tables in my SQL Server (2012) DB:

Tbl1:

ID:     Col1:     Col2:     Col3:
1       Val1      Val2      Val3
2       <NULL>    Val2      <NULL>
3       Val1      <NULL>    Val3
4       Val1      <NULL>    Val3

Tbl2:

ID:     Col1:     Col2:     Col3:
1       Val1      Val2      Val3
2       <NULL>    Val2      <NULL>
3       <NULL>    <NULL>    Val3
5       <NULL>    <NULL>    Val3

And, at this point, all I want to see is:

  1. Any rows that are in one table but not the other (based on ID pk)
  2. If the ID is in both tables, then are the same columns populated (not caring specifically about the values yet).

I'm just trying to come up with a SQL to just let me know which IDs have discrepancies.

My ideal output would look as follows:

Tbl1_ID:       Tbl2_Id:       Discrepancy:
1              1              0
2              2              0
3              3              1
4              <NULL>         1
<NULL>         5              1  

My testing SQL so far is this:

DECLARE 
@Tbl1 TABLE (ID INT, Col1 VARCHAR(10), Col2 VARCHAR(10), Col3 VARCHAR(10))
;
DECLARE
@Tbl2 TABLE (ID INT, Col1 VARCHAR(10), Col2 VARCHAR(10), Col3 VARCHAR(10))
;

INSERT INTO @Tbl1 (ID, Col1, Col2, Col3)
VALUES
    (1, 'Val1', 'Val2', 'Val3')
    ,(2, NULL   , 'Val2', NULL)
    ,(3, 'Val1', NULL, 'Val3')
    ,(4, 'Val1', NULL, 'Val3')
;

INSERT INTO @Tbl2 (ID, Col1, Col2, Col3)
VALUES
    (1, 'Val1', 'Val2', 'Val3')
    ,(2, NULL   , 'Val2', NULL)
    ,(3, NULL, NULL, 'Val3')
    ,(5, NULL, NULL, 'Val3')
;


SELECT
     [@Tbl1].ID AS Tbl1_ID
    ,[@Tbl2].ID AS Tbl2_ID
    , -- Some kind of comparison to let me know if all columns are populated the same
     AS Discrepancy
FROM
    @Tbl1
    FULL JOIN @Tbl2
    ON [@Tbl1].ID = [@Tbl2].ID

Is there some good way to accomplish this?

Thanks!!


回答1:


For the discrepancy column, just use a case statement.

case when [@Tbl1].ID = [@Tbl2].ID then 0 else 1 end

Or for all columns...

case case when [@Tbl1].ID = [@Tbl2].ID 
               and isnull([@Tbl1].Col1,'random') = isnull([@Tbl2].Col1,'random')
               and ...
               then 0 else 1 end


来源:https://stackoverflow.com/questions/51865261/sql-server-compare-2-tables-for-data-existing-in-the-same-columns-without-chec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!