Skip to main content

Nested $Order Loops

Using a series of nested $Order loops (one for each level within a branch of the tree) allows you to reach the leaves, which are the ID numbers. You then use the ID to go back to the data global and retrieve whatever information you desire. Here's an example, using the name index. For each last name, a new loop is called that will find all first names for that last name. And for each full name, a new loop finds all the ID numbers for that name. The ID is used to get the rest of the data from ^PersonD.

VS Code - ObjectScript

/// examples for ObjectScript Tutorial
Class ObjectScript.Examples

/// Loop through the name index and display the records
ClassMethod NameLoop()
    // loop through last names
    set ln = ""
    for {
        set ln = $order(^PersonI("Name", ln))
        quit:(ln = "")
        // for each last name, loop through first names
        set fn = ""
        for {
            set fn = $order(^PersonI("Name", ln, fn))
            quit:(fn = "")
            // for each last name and first name, loop through id numbers
            set id = ""
            for {
                set id = $order(^PersonI("Name", ln, fn, id))
                quit:(id = "")
                // once you have an id number, get the data and display it
                set rec = ^PersonD(id)
                write !, $list(rec, 1),
                      ?15, $list(rec, 2),
                      ?30, $zdate($list(rec, 3), 2)
Copy code to clipboard
Testing using the Terminal

USER>do ##class(ObjectScript.Examples).NameLoop()

Agee,Tommie    617-333-3333   09 Aug 42
Jones,Bobby    333-444-5555   10 Feb 70
Jones,Cleon    111-111-1111   04 Aug 42
Swoboda,Ron    222-222-2222   08 Jun 44
Copy code to clipboard
FeedbackOpens in a new window