Hi All,
I am having problem with UNIQUE CONSTRAINT. I am trying to update a table and getting the violation error. Here is the over view. We have a table called ActivityAttendee. ActivityAttendee has the following columns. The problem to debug is this table has over 23 million records. How can I catch where my query is going wrong?
ActivityAttendeeID INT PRIMARY KEY IDENTITY(1,1)
,ActivityID INT NOT NULL (Foreign key to parent table Activity)
,AtendeeTypeCodeID INT NOT NULL
,ObjectID INT NOT NULL
,EmailAddress VARCHAR(255) NULL
UNIQUE KEY is on ActivityID,AtendeeTypeCodeID,ObjectID,EmailAddress
We have a requirement where we need to update the ObjectID. There is a new mapping where I dump that into a temp table #tempActivityMapping (intObjectID INT NOT NULL, intNewObjectID INT NULL)
The problem is ActivityAttendee table might already have the new ObjectID and the unique combination.
For example: ActivityAttendee Table have the following rows
1,1,1,1,NULL
2,1,1,2,NULL
3,1,1,4,'abc'
AND the temp table has 2,1
So essentially when I update in this scenario, It should ignore the second row because, if I try updating that there will be a violation of key as the first record has the exact value. When I ran my query on test data it worked fine. But for 23 million records, its going wrong some where and I am unable to debug that. Here is my query
UPDATE AA SET AA.ObjectID = TMP.NewObjectID FROM dbo.ActivityAttendee AA INNER JOIN #tmpActivityMapping TMP ON AA.ObjectID = TMP.ObjectID WHERE TMP.NewObjectID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.ActivityAttendee AA1 WHERE AA1.ActivityID = AA.ActivityID AND AA1.AttendeeTypeCodeID = AA.AttendeeTypeCodeID AND AA1.ObjectID = TMP.NewObjectID AND ISNULL(AA1.EmailAddress,'') = ISNULL(AA.EmailAddress,'')