I am creating a script that is to "merge" and remove duplicate rows from the table. The table contains address information and uses a whole field to store information about email in the form of bit flags (column name lngValue). For example, lngValue and 1 == 1 means its primary address.
There are cases when the same letter is entered twice, but sometimes with different lngValues. To solve this problem, I need to take lngValue from all duplicates and assign them to one saved record and delete the rest.
My biggest headache, as far as it was with the "merging" of records. What I want to do is bitwise or all lngValues of duplicate entries together. Here is what I still have, which only finds the value of all lngValues bitwise or together.
Warning: confusing code ahead
declare @duplicates table
(
lngInternetPK int,
lngContactFK int,
lngValue int
)
insert into @duplicates (lngInternetPK, lngContactFK, lngValue)
(
select tblminternet.lngInternetPK, tblminternet.lngContactFK, tblminternet.lngValue from tblminternet inner join
(select strAddress, lngcontactfk, count(*) as count from tblminternet where lngValue & 256 <> 256 group by strAddress, lngcontactfk) secondemail
On tblminternet.strAddress = secondemail.strAddress and
tblminternet.lngcontactfk = secondemail.lngcontactfk
where count > 1 and tblminternet.strAddress is not null and tblminternet.lngValue & 256 <> 256
)
update @duplicates set lngValue = t.val
from
(select (sum(dupes.lngValue) & 65535) as val from
(select here.lngInternetPK, here.lngContactFK, here.lngValue from tblminternet here inner join
(select strAddress, lngcontactfk, count(*) as count from tblminternet where lngValue & 256 <> 256 group by strAddress, lngcontactfk) secondemail
On here.strAddress = secondemail.strAddress and
here.lngcontactfk = secondemail.lngcontactfk
where count > 1 and here.strAddress is not null and here.lngValue & 256 <> 256) dupes, tblminternet this
where this.lngContactFK = dupes.lngContactFK
) t
where lngInternetPK in (select lngInternetPK from @duplicates)
Edit:
As requested here are some sample data:
Table Name: tblminternet Column
Names:
lngInternetPK
lngContactFK
lngValue
strAddress
Example line 1:
lngInternetPK: 1
lngContactFK: 1
lngValue: 33
strAddress: " me@myaddress.com "
2:
lngInternetPK: 2
lngContactFK: 1
lngValue: 40
strAddress: "me@myaddress.com"
, :
lngInternetPK: 1
lngContactFK: 1
lngValue: 41
strAddress: "me@myaddress.com"
:
, ( ).