有几种情况需要检查
- 表 2 中的新行
- 表 2 中删除的行
- 表 2 中的更改值或值
注意最后一点:几个值可能会改变。
此代码返回一系列标志以显示已更改的内容
CREATE TABLE #test1 (ID int, Impact varchar(100), NAME varchar(100), STATUS char(1));
CREATE TABLE #test2 (ID int, Impact varchar(100), NAME varchar(100), STATUS char(1));
GO
INSERT #test1 VALUES (1, 'xx', 'name1', 'A'), (2, 'zz', 'name2', 'B'), (3, 'xx', 'name3', 'B'), (4, 'xx', 'name4', 'A');
INSERT #test2 VALUES (1, 'xx', 'name1', 'A'), /*(2, 'xx', 'name2', 'B'),*/ (3, 'xx', 'name33', 'B'), (4, 'yy', 'name4', 'A'), (5, 'zz', 'name5', 'B');
GO
SELECT
0 AS MissingRowinT2,
0 AS NewRowinT2,
CASE WHEN T1.STATUS <> T2.STATUS THEN 1 ELSE 0 END AS StatusChanged,
CASE WHEN T1.NAME <> T2.NAME THEN 1 ELSE 0 END AS NAMEChanged,
CASE WHEN T1.Impact <> T2.Impact THEN 1 ELSE 0 END AS ImpactChanged,
*
FROM
#test1 T1
JOIN
#test2 T2 ON T1.ID = T2.ID
WHERE NOT EXISTS
(
select T1.*
INTERSECT
select T2.*
)
UNION ALL
SELECT
SIGN(ISNULL(T2.ID, 1)), SIGN(ISNULL(T1.ID, 1)), 0, 0, 0, *
FROM
#test1 T1
FULL OUTER JOIN
#test2 T2 ON T1.ID = T2.ID
WHERE
T1.ID IS NULL OR T2.ID IS NULL
GO
如果您需要说明
SELECT
SUBSTRING(
CASE WHEN T1.STATUS <> T2.STATUS THEN ',Status' ELSE '' END +
CASE WHEN T1.NAME <> T2.NAME THEN ',NAME,' ELSE '' END +
CASE WHEN T1.Impact <> T2.Impact THEN ',Impact' ELSE '' END,
2, 8000) AS WhatCHanged,
*
FROM
#test1 T1
JOIN
#test2 T2 ON T1.ID = T2.ID
WHERE NOT EXISTS
(
select T1.*
INTERSECT
select T2.*
)
UNION ALL
SELECT
CASE WHEN T1.ID IS NULL THEN 'NewRow' ELSE 'Deleted Row' END, *
FROM
#test1 T1
FULL OUTER JOIN
#test2 T2 ON T1.ID = T2.ID
WHERE
T1.ID IS NULL OR T2.ID IS NULL
GO