-- Citations, Invisible Revealed - Revert - Bitwise.sql
/*
2015-12-19 by Tom Holden
rev 2015-12-24 unsets 1st bit of CitationTable.Flags rather than setting Flags to 0, 
  compatible with future operations by RootsMagic using this field. 

Reverts invisible citations converted by 
"Citations, Invisible - Convert to Personals + Flagged.sql"
to CitationTable.OwnerType=7 and CitationTable.Flags=Flags-1 from 0 and bit1=1, respectively,
and the CitationTable.OwnerID to the NameID of the person's Primary Name,
thus restoring them to being citations for the primary Name.
*/

BEGIN ;
UPDATE OR ROLLBACK CitationTable
SET OwnerID = 
(
 SELECT NameTable.NameID 
 FROM CitationTable AS Old
 LEFT JOIN NameTable
 ON Old.OwnerID = NameTable.OwnerID
 WHERE Old.CitationID = CitationTable.CitationID
 AND +NameTable.IsPrimary
),
OwnerType = 7,
Flags = Flags - 1
WHERE CitationID IN
(
 SELECT DISTINCT CitationID
 FROM CitationTable
 LEFT JOIN NameTable
 ON CitationTable.OwnerID = NameTable.OwnerID
 WHERE CitationTable.Flags & 1 --rev 2015-12-24 test if 1st bit set
)
;
COMMIT ;