Skip to content

Instantly share code, notes, and snippets.

@PhDuck
Last active July 29, 2022 09:36
Show Gist options
  • Save PhDuck/6e37cf102309fab7056ce585dc205ec4 to your computer and use it in GitHub Desktop.
Save PhDuck/6e37cf102309fab7056ce585dc205ec4 to your computer and use it in GitHub Desktop.
Generic code for attempting to delete all data in Business Central
codeunit 50103 DeleteAll
{
local procedure DoYouFeelLuckyPunk()
var
cust: Record Customer;
begin
DeleteAllData();
if (System.Random(2) = 1) then
Error('You were lucky! All your data was not deleted! I dare you to try again ;)');
// It makes no semantic difference if the DeleteAllData() call was moved here.
// However performance wise it is smarter to first delete when we know we must.
end;
local procedure DeleteAllData()
var
tab: Record "Table Metadata";
company: Record Company;
begin
tab.SetFilter(tab.ObsoleteState, '<>%1', tab.ObsoleteState::Removed);
tab.SetRange(tab.TableType, tab.TableType::Normal); // We cannot ensure others are setup :(
if (tab.FindSet()) then
repeat
if tab.DataPerCompany then begin
if (company.FindSet()) then
repeat
CheckAndDeleteTable(company.Name, tab.ID);
until company.Next() = 0;
end else
CheckAndDeleteTable(Database.CompanyName, tab.ID);
until (tab.Next() = 0) OR (tab.ID >= Database::Object); // Open will throw on system tables.
end;
local procedure CheckAndDeleteTable(companyName: Text; tableId: Integer)
var
tabRef: RecordRef;
begin
tabRef.Open(tableId, false, companyName);
tabRef.SecurityFiltering(SecurityFiltering::Ignored); // Don't let them hide stuff!
// We cannot delete what we do not have permissions to :(
// so rather than erroring out and deleteting nothing, lets delete as much as possible!
if (tabRef.WritePermission) then begin
// We cannot ensure this call will succeed since an event subscriber may throw an error :(
tabRef.DeleteAll(false);
end;
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment