====== pears.DBCleanupOrphanTagValue ======
Generated schema reference. Regenerate this page from the SQL unload; keep hand-maintained business notes in the narrative namespace.
===== Original SQL =====
create function "pears"."DBCleanupOrphanTagValue"(
/* Application Maintained Function / Procedure - DO NOT EDIT*/
in "countordo" char(1) )
returns integer
begin
declare @RC integer;
set @RC = 0;
if "countordo" = 'C' then
select "count"() into @RC from "tagvalue"
where(((("taglocation" = 'P') or("taglocation" like 'A%')) and not exists(select * from "person" where "personid" = "tagvalue"."id"))
or(("taglocation" = 'E') and not exists(select * from "employment" where "employmentid" = "tagvalue"."id"))
or(("taglocation" = 'C') and not exists(select * from "company" where "companyid" = "tagvalue"."id"))
or(("taglocation" like 'V%') and not exists(select * from "vacancy" where "vacancyid" = "tagvalue"."id"))
or(("taglocation" like 'L%') and not exists(select * from "placement" where "placementid" = "tagvalue"."id"))
or(("taglocation" = 'U') and not exists(select * from "staff" where "staffid" = "tagvalue"."id"))
or(("taglocation" = 'N') and not exists(select * from "contactevent" where "contacteventid" = "tagvalue"."id")));
return @RC
end if;
delete from "tagvalue" where(("taglocation" = 'P') or("taglocation" like 'A%'))
and not exists(select * from "person" where "personid" = "tagvalue"."id");
set @RC = @RC+(select @@rowcount);
delete from "tagvalue" where("taglocation" = 'C')
and not exists(select * from "company" where "companyid" = "tagvalue"."id");
delete from "tagvalue" where("taglocation" = 'E')
and not exists(select * from "employment" where "employmentid" = "tagvalue"."id");
set @RC = @RC+(select @@rowcount);
delete from "tagvalue" where("taglocation" like 'V%')
and not exists(select * from "vacancy" where "vacancyid" = "tagvalue"."id");
set @RC = @RC+(select @@rowcount);
delete from "tagvalue" where("taglocation" like 'L%')
and not exists(select * from "placement" where "placementid" = "tagvalue"."id");
set @RC = @RC+(select @@rowcount);
delete from "tagvalue" where("taglocation" = 'U')
and not exists(select * from "staff" where "staffid" = "tagvalue"."id");
set @RC = @RC+(select @@rowcount);
delete from "tagvalue" where("taglocation" = 'N')
and not exists(select * from "contactevent" where "contacteventid" = "tagvalue"."id");
set @RC = @RC+(select @@rowcount);
call "AuditLog"('CLEANUP',null,"string"(@RC,' Unattached Question Answers deleted '),null,null);
return @RC
end