Posts Tagged ‘Operator’

It is a very common scenario when you need to match a source table and a target table to find the missing (mismatch) rows across the result sets. We usually do it for multiple purposes specially at the time of audit or data migration etc.

Problem :
We usually use logical operators (NOT IN, Exists) to find the difference between two result sets. However, if you need to match each row by each row & each column by each column, it would be very difficult to achieve it via above mentioned logical operators.

Sample :
Let me create a sample to demonstrate the problem and solution.

--This script is compatible with SQL Server 2005
USE [AdventureWorks2012]
--Create a sample table
CREATE TABLE [HumanResources].[Department_Sample](
[DepartmentID] [smallint] NOT NULL,
[Name] [dbo].[Name] NOT NULL,
[GroupName] [dbo].[Name] NOT NULL,
[ModifiedDate] [datetime] NOT NULL,

--Insert records into the sample table from actual table
INSERT INTO [HumanResources].[Department_Sample]
SELECT * FROM [HumanResources].[Department]

--Update a single record in the sample table
--to differentiate it from actual
UPDATE [HumanResources].[Department_Sample]
SET [Name] = 'Business Development'
WHERE DepartmentID=2

--Insert a record in the original table
INSERT INTO [HumanResources].[Department]
,'Executive General and Administration'
--Delete a record from the sample table
DELETE FROM [HumanResources].[Department_Sample]
WHERE [DepartmentID]=11
SELECT * FROM [HumanResources].[Department]

find missing result set.1.1

Solution :
As mentioned above, I created a sample table, copied data from original table in it and then modified & inserted the data in the sample table & original table respectively. Now, in order to find the the missing (mismatched) records across the result set, we need to use EXCEPT operator. Given below is the script that will ONLY show the missing rows in the sample table (Target Table).

--This script is compatible with SQL Server 2005
USE AdventureWorks2012
--Source Table
SELECT * FROM [HumanResources].[Department]
--Target table
SELECT * FROM [HumanResources].[Department_Sample]

find missing result set.1.2

Conclusion :
Whenever you need to find the missing (mismatch) row across the result sets, always use EXCEPT operator to make your life easier.

Read Full Post »