Groups | Blog | Home
all groups > sql server (alternate) > december 2004 >

sql server (alternate) : Merge two rows in the same table


laurenq uantrell
12/13/2004 1:01:51 PM
I want to create a stored procedure that will merge columns from two
rows that contain duplicated contacts.

I have can easily identify the duplicates and extract the UniqueIDs as
parameters, but I can't figure out how to construct the actual update
SQL.

@KeeperID int,
@DupeID int

Update Contacts
SET
a.Info1 = LEFT(TRIM(IsNull(a.info1,'') + ' ' IsNull(b.Info1,''))255),
a.Info2 = LEFT(TRIM(IsNull(a.info2,'') + ' ' IsNull(b.Info2,'')),255),
etc, etc...
FROM
(here's what I can't figure out)
Contacts a ID = @KeeperID
Contacts b ID = @DupeID
--CELKO--
12/13/2004 3:26:20 PM
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.

Of course, you know better than to use the dangerous and proprietary
UPDATE.. FROM.. syntax you showed in your personal pseudo-code.
John Bell
12/13/2004 9:13:42 PM
Hi

Try:

Update A
SET
Info1 = LEFT(TRIM(IsNull(a.info1,'') + ' ' + IsNull(b.Info1,''))255),
Info2 = LEFT(TRIM(IsNull(a.info2,'') + ' ' + IsNull(b.Info2,'')),255),
etc, etc...
FROM
Contacts a, Contacts b
WHERE A.ID = @KeeperID
AND B.ID = @DupeID

If you had multiple contacts you could create a table (linkingTable)
containing origin PrimaryContactId and SecondaryContactId, something like:

INSERT INTO LinkingTable(PrimaryContactId, SecondaryContactId) VALUES (
@KeeperId, @DupeID )

Update A
SET
Info1 = LEFT(TRIM(IsNull(a.info1,'') + ' ' + IsNull(b.Info1,''))255),
Info2 = LEFT(TRIM(IsNull(a.info2,'') + ' ' + IsNull(b.Info2,'')),255),
etc, etc...
FROM Contacts a
JOIN linkingTable l on a.ContactId = l.PrimaryContactId
JOIN Contacts b On l.SecondaryContactId = b.ContactId

John


[quoted text, click to view]

AddThis Social Bookmark Button