Say that a developer has thousands of records to modify on a database. For example, a library wants to format the titles of books a certain way. If the developer loops through the records with a for loop, the program has to take the record from the database, modify the record, and then send it back to the server. This can run very slowly especially with so many records. It would be much faster to have a command that runs on the server directly, and this is what occurs with the APPLY TO SELECTION command.
The APPLY TO SELECTION command allows the developer to apply a statement or method on all records of a table's selection directly on the server. The developer can modify all unlocked records quickly this way.
In this example, there is a database that include book tiles in a library. This method, libraryFormat, simply moves the word "The" in a title to the end of the title string if it starts with "The" for the sake of sorting by title ignoring "The". This is only one example of how records could be mass modified and implementation may differ depending on the behavior the developer wants.
//libraryFormat Method: Brings the word "The" to the end of the title for sorting #DECLARE($string : Text)->$result : Text $firstletters:=Substring($string; 0; 4) If ($firstletters="The ") $result:=Substring($string; 5)+", The" Else $result:=$string End if |
Here is how one can call this method using APPLY TO SELECTION when the entire Library table is selected. APPLY TO SELECTION saves the records with the new value from the statement in the second parameter.
ALL RECORDS([Library]) APPLY TO SELECTION([Library]; [Library]Title:=libraryFormat([Library]Title)) |