-- Citations, Invisible Revealed - Revert.sql
/*
2015-12-19 by Tom Holden

Reverts invisible citations converted by 
"Citations, Invisible - Convert to Personals + Flagged.sql"
to CitationTable.OwnerType=7 and CitationTable.Flags=0 from 0 and 7, 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 = 0
WHERE CitationID IN
(
 SELECT DISTINCT CitationID
 FROM CitationTable
 LEFT JOIN NameTable
 ON CitationTable.OwnerID = NameTable.OwnerID
 WHERE CitationTable.Flags = 7 --AND +NameTable.IsPrimary
)
;
COMMIT ;