如何在MSSQL中将两个数据库连接在一起并比较行,包括空值?

时间:2017-07-27 08:50:54

标签: sql sql-server database sql-server-2012

我正在尝试比较两个数据库(相同,一个是备份),我想在其中一个数据库中包含任何可能读为空的缺失行。

我有一个两个数据库(SUS_Database_1SUS_Database_2),它们都有一个transaction表和名为transacation_iddatetime的列。我想比较两个交易表,包括2个数据库之间的所有NULLS。

就我而言

SELECT db1.transaction_id, db1.datetime  
FROM SUS_Database_1.dbo.transaction db1 WITH (nolock) 
  JOIN SUS_Database_2.dbo.transaction db ON db2.transaction_id = 
db1.transaction_id
SELECT db2.transaction_id, db2.datetime  
FROM SUS_Database_2.dbo.transaction db2 WITH (nolock) 
UNION ALL
SELECT db2.transaction_id, db2.datetime  
FROM SUS_Database_2.dbo.transaction db2 WITH (nolock)
 JOIN SUS_Database_1.dbo.transaction db ON db1.transaction_id = 
db2.transaction_id
SELECT db1.transaction_id, db1.datetime   
FROM SUS_Database_1.dbo.transaction db1 WITH (nolock) 

这将返回两个独立输出中的值,而不是将它们全部合并在一起

2 个答案:

答案 0 :(得分:0)

检查一下

SELECT db1.transaction_id, db1.datetime  
FROM SUS_Database_1.dbo.transaction db1 WITH (nolock) 
  JOIN SUS_Database_2.dbo.transaction db ON db2.transaction_id = 
db1.transaction_id
UNION ALL
SELECT db2.transaction_id, db2.datetime  
FROM SUS_Database_2.dbo.transaction db2 WITH (nolock) 
UNION ALL
SELECT db2.transaction_id, db2.datetime  
FROM SUS_Database_2.dbo.transaction db2 WITH (nolock)
 JOIN SUS_Database_1.dbo.transaction db ON db1.transaction_id = 
db2.transaction_id
SELECT db1.transaction_id, db1.datetime   
FROM SUS_Database_1.dbo.transaction db1 WITH (nolock) 

答案 1 :(得分:0)

有点不清楚"比较表"是什么意思,但通常是你想要的三个条件:

  1. 对于transaction_id中包含不同值的datetime行(包括空值)
  2. 仅存在于DB1中的行
  3. 仅存在于DB2中的行
  4. 你可以通过一个简单的FULL JOIN获得所有三个查询:

    SELECT 
        db1.transaction_id AS db1_transaction_id 
      , db1.datetime AS db1_datetime
      , db2.transaction_id AS db2_transaction_id
      , db2.datetime AS db2_datetime 
    FROM SUS_Database_1.dbo.transaction db1
    FULL JOIN SUS_Database_2.dbo.transaction db2 ON db2.transaction_id = db1.transaction_id
    WHERE db1.datetime IS NULL 
       OR db2.datetime IS NULL 
       OR db1.datetime <> db2.datetime