Skip to main content

Notifications

Small and medium business | Business Central, N...
Suggested answer

searching any table for any field in procedure Dynamics Business Central AL

Posted on by 7
I'm working on optimizing some AL code in Dynamics Business Central, and I've noticed that there's a lot of redundant code when searching for records based on specific fields like name or age. I'd like to refactor this into a more generic function that can handle searching any table for any field.
```
procedure findEmployeeNo(Name:Text[20]; Age:Integer): code[20]
begin
            // search by Name
            Employee.Reset();
            Employee.ChangeCompany(company.Name);
            Employee.Setrange(/Name/, Name);
            If Employee.FindFirst() then begin
                exit(Employee./No./)
            end;
            // search by Age
            Employee.Reset();
            Employee.Setrange(/Age/, Age);
            If Employee.FindFirst() then begin
                exit(Employee./No./)
            end;
    exit('');
end;

```
Refactoring AL Code to:
```
procedure findEmployeeNo(Name:Text[20]; Age:Integer): code[20]
var Employee: record Employee;
begin
            Employee := findFieldData('Employee', 'Name', Name)
            If Employee then begin
                exit(Employee./No./)
            end;
            Employee := findFieldData('Employee', 'Age', Age)
            If Employee then begin
                exit(Employee./No./)
            end;
    exit('');
end;

```
Categories:
  • Suggested answer
    YUN ZHU Profile Picture
    YUN ZHU 73,565 Super User 2024 Season 2 on at
    searching any table for any field in procedure Dynamics Business Central AL
    Hi, sorry, what is your problem?
    If you want to modify the standard code, this is not possible on SaaS.
    If you add new methods, you can use them in your custom functions. This is no problem.
    If you want to write more generic function, it is recommended to use RecordRef Data Type and FieldRef Data Type.
     
    Hope this helps.
    Thanks.
    ZHU

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans