Skip to main content

Notifications

Business Central forum
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 68,242 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

Helpful resources

Quick Links

Dynamics 365 Community Update – Sep 9th

Welcome to the next edition of the Community Platform Update. This is a weekly…

Dynamics 365 Community Newsletter - August 2024

Catch up on the latest D365 Community news

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 290,186 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 227,996 Super User 2024 Season 2

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans