Monday, July 7, 2008

Comparing 2 Results Sets to see if they are identical

A post on the MSDN forums asked how to check if two results sets were identical, and Jim McLeod offered a pretty simple method to check this, that was worth sharing:

SELECT CASE WHEN COUNT(*) = 0 THEN 'Same' ELSE 'Different' END
FROM
(
(
SELECT * FROM Table1
EXCEPT
SELECT
* FROM Table2
)
UNION
(
SELECT * FROM Table2
EXCEPT
SELECT
* FROM Table1
)
)
dv


This query basically gets all the rows that are in Table 1 but not Table 2, then UNIONS all rows that are in Table 2 but not Table 1.  If there's zero rows for both, the result sets must be the same.



Fast Simple, and easy to implement.

No comments:

Post a Comment