我正在尝试比较两个数据库(相同,一个是备份),我想在其中一个数据库中包含任何可能读为空的缺失行。
我有一个两个数据库(SUS_Database_1
和SUS_Database_2
),它们都有一个transaction
表和名为transacation_id
和datetime
的列。我想比较两个交易表,包括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)
这将返回两个独立输出中的值,而不是将它们全部合并在一起
答案 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)
有点不清楚"比较表"是什么意思,但通常是你想要的三个条件:
transaction_id
中包含不同值的datetime
行(包括空值)你可以通过一个简单的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