SQL - Bill Not Found From Appointment
v7,v6
Query below will find appointment that are linked to a bill number in the database that does not exist or is cancelled. The update query will set the appointments back to due so they don't roll over or can be cancelled. Check which appointments are linked to missing bills select DM."Ref_Number", DM."Cln_Num", (select CM."Last_Name" from "Client_Main" CM where DM."Cln_Num" = CM."Ref_Number") as "Lastname", DM."Sub_Num", (select AM."Name" from "Animal_Main" AM where DM."Sub_Num" = AM."Ref_Number") as "Anm_Name", DM."Bil_Num", DM."Site_Ref", DM."Dry_Num", (select DP."Dry_Name" from "Diary_Profile" DP where DM."Dry_Num" = DP."Dry_Number" and DM."Site_Ref" = DP."Site_Ref") as "Diary_Name", DM."Diary_Status",DM."Notes", DM."Start", DM."Finish" from "Diary_Main" DM where "Date" >= current_Date and (not exists (select BM."Ref_Number" from "Bill_Main" BM where BM."Ref_Number" = DM."Bil_Num") or exists (select * from "Bill_Main" BM where BM."Ref_Number" = DM."Bil_Num" and BM."Acc_State" = 59)) and DM."Bil_Num" is not null and DM."Diary_Status" in (8,10) order by "Dry_Num" Set Appointments back to Due (repeat for each ref number above) execute block returns ("Ref_Number" NUMERIC (18, 0)) as begin execute procedure "Set_Trn_Context" ('Dont_Log_Changes','Y'); for select distinct DM."Ref_Number" from "Diary_Main" DM left outer join "Bill_Main" BM on BM."Ref_Number" = DM."Bil_Num" where DM."Date" >= current_Date and DM."Diary_Status" in (8,10) and (BM."Ref_Number" is null or BM."Acc_State" = 59) into "Ref_Number" do begin update "Diary_Main" DM set DM."Bil_Num" = null, DM."Diary_Status" = 0 where DM."Ref_Number" = :"Ref_Number"; suspend; end execute procedure "Set_Trn_Context" ('Dont_Log_Changes',null); end