Exercise: Build and consume a query solution
Build a query-backed customer sales solution in an existing AL project and publish it only to a Business Central online sandbox. Use standard sandbox sample data; the exercise creates no custom tables or data.
Prepare the sandbox project
Use an existing AL project connected to a sandbox with the standard sample company. Confirm that the project object range includes IDs 70650 through 70699. Never publish these exercise objects to a production environment.
In VS Code settings, enable report layout generation:
{
"al.compilationOptions": {
"generateReportLayout": true
}
}
Add the following four AL objects to the project. The query groups matching customer ledger entries by customer. Its inner join omits customers without matching invoices or credit memos.
Create the query and AL reader
query 70650 "Customer Sales Summary"
{
QueryType = Normal;
Caption = 'Customer Sales Summary';
UsageCategory = ReportsAndAnalysis;
OrderBy = descending(TotalSalesAmount);
elements
{
dataitem(Customer; Customer)
{
column(CustomerNo; "No.")
{
}
column(CustomerName; Name)
{
}
dataitem(CustLedgerEntry; "Cust. Ledger Entry")
{
DataItemLink = "Customer No." = Customer."No.";
SqlJoinType = InnerJoin;
DataItemTableFilter = "Document Type" = filter(Invoice | "Credit Memo");
filter(PostingDateFilter; "Posting Date")
{
}
column(EntryCount)
{
Method = Count;
}
column(TotalSalesAmount; "Sales (LCY)")
{
Method = Sum;
}
}
}
}
}
codeunit 70650 "Customer Sales Reader"
{
procedure Calculate(FromDate: Date; ToDate: Date; var ResultRows: Integer; var GrandTotal: Decimal)
var
CustomerSalesSummary: Query "Customer Sales Summary";
begin
ResultRows := 0;
GrandTotal := 0;
if (FromDate = 0D) or (ToDate = 0D) then
Error('Enter both a start date and an end date.');
if FromDate > ToDate then
Error('The start date must be on or before the end date.');
CustomerSalesSummary.SetRange(PostingDateFilter, FromDate, ToDate);
CustomerSalesSummary.Open();
while CustomerSalesSummary.Read() do begin
ResultRows += 1;
GrandTotal += CustomerSalesSummary.TotalSalesAmount;
end;
CustomerSalesSummary.Close();
end;
}
ResultRows counts customer groups returned by the query, not individual ledger entries. The query's EntryCount column counts matching entries within each customer group. GrandTotal sums the customer-group totals.
Add the report and page actions
The report uses a filtered Integer data item to read the query. Its date request fields default to January 1 of the WorkDate year through WorkDate. The Excel layout is generated when you package the project with layout generation enabled.
report 70650 "Customer Sales Summary"
{
UsageCategory = ReportsAndAnalysis;
ApplicationArea = All;
DefaultRenderingLayout = CustomerSalesSummary;
dataset
{
dataitem(Integer; Integer)
{
DataItemTableView = sorting(Number) where(Number = filter(1..));
column(CustomerNo; CustomerSalesSummary.CustomerNo)
{
}
column(CustomerName; CustomerSalesSummary.CustomerName)
{
}
column(EntryCount; CustomerSalesSummary.EntryCount)
{
}
column(TotalSalesAmount; CustomerSalesSummary.TotalSalesAmount)
{
}
trigger OnPreDataItem()
begin
CustomerSalesSummary.SetRange(PostingDateFilter, FromDate, ToDate);
CustomerSalesSummary.Open();
end;
trigger OnAfterGetRecord()
begin
if not CustomerSalesSummary.Read() then
CurrReport.Break();
end;
trigger OnPostDataItem()
begin
CustomerSalesSummary.Close();
end;
}
}
requestpage
{
layout
{
area(Content)
{
group(Options)
{
field(FromDate; FromDate)
{
ApplicationArea = All;
Caption = 'From date';
}
field(ToDate; ToDate)
{
ApplicationArea = All;
Caption = 'To date';
}
}
}
}
}
rendering
{
layout(CustomerSalesSummary)
{
Type = Excel;
LayoutFile = './Layouts/CustomerSalesSummary.xlsx';
Caption = 'Customer sales summary';
Summary = 'Customer sales by customer for the selected posting date range.';
}
}
trigger OnInitReport()
begin
FromDate := DMY2Date(1, 1, Date2DMY(WorkDate(), 3));
ToDate := WorkDate();
end;
trigger OnPreReport()
begin
if (FromDate = 0D) or (ToDate = 0D) then
Error('Enter both a start date and an end date.');
if FromDate > ToDate then
Error('The start date must be on or before the end date.');
end;
var
CustomerSalesSummary: Query "Customer Sales Summary";
FromDate: Date;
ToDate: Date;
}
pageextension 70650 "Customer Query Actions" extends "Customer List"
{
actions
{
addlast(Processing)
{
action(ValidateCustomerSalesQuery)
{
ApplicationArea = All;
Caption = 'Validate sales query';
Image = Calculate;
ToolTip = 'Calculate customer sales for the current year and display the returned group count and total.';
trigger OnAction()
var
CustomerSalesReader: Codeunit "Customer Sales Reader";
FromDate: Date;
ToDate: Date;
ResultRows: Integer;
GrandTotal: Decimal;
begin
FromDate := DMY2Date(1, 1, Date2DMY(WorkDate(), 3));
ToDate := WorkDate();
CustomerSalesReader.Calculate(FromDate, ToDate, ResultRows, GrandTotal);
Message('Customer groups: %1, total sales (LCY): %2', ResultRows, GrandTotal);
end;
}
action(RunCustomerSalesSummary)
{
ApplicationArea = All;
Caption = 'Run customer sales summary';
Image = Report;
RunObject = report "Customer Sales Summary";
ToolTip = 'Open the customer sales summary report for a selected posting date range.';
}
}
}
}
Package, publish, and validate
- In VS Code, run AL: Package. Confirm that the generated
Layouts/CustomerSalesSummary.xlsxincludes the report dataset structure. - Edit the generated workbook layout without deleting or renaming its dataset structure, then run AL: Package again if needed.
- Publish the extension to the sandbox. In the query object, run the unfiltered query and inspect its customer groups, entry counts, and totals.
- On Customer List, select Validate sales query and confirm that the codeunit returns a row count and total without opening a page.
- Select Run customer sales summary, use the same date range as the query check, and run the report.
- Use Send to > Microsoft Excel Document with the data-only option. Compare the report rows and total with the codeunit message for the same date range. Use the unfiltered direct query to validate the grouping shape separately.
| Validation | Expected observation |
|---|---|
| Unmatched customer | A customer with no matching invoice or credit memo doesn't appear because the join is inner. |
| Multiple ledger entries | Entries for one customer appear in one customer group, with EntryCount and TotalSalesAmount reflecting the matching entries. |
| Date filter | The report and codeunit return results for the selected inclusive posting date range. |
| Reconciliation | The report dataset and codeunit agree on customer-group count and total for the same date filter. The direct query confirms the unfiltered grouping shape. |
No fixed row count or amount is expected because sandbox data varies. If results differ, check the join type, document-type filter, date range, grouping columns, and whether the consumer reused an old query instance.
| Symptom | Check |
|---|---|
| The query returns no rows | Confirm matching ledger entries, invoice or credit memo document types, and the posting date range. |
| Customer totals look too large | Check join cardinality and confirm that a one-to-many join doesn't repeat the measure. |
| Runtime filters behave unexpectedly | Set filters on defined query columns or filter rows before Open, and check static-filter intersection. |
| The report stops or repeats incorrectly | Verify the Integer filter starts at 1, Read runs in OnAfterGetRecord, and Close runs in OnPostDataItem. |
| The Excel layout doesn't render | Repackage with report layout generation enabled and preserve the generated dataset structure in the workbook. |
When validation is complete, uninstall the exercise extension from the sandbox. The exercise adds no custom tables or data to clean up.