Sunday, March 16, 2014

Counting subscripts in GTM using a simple method

Once you have many records inside your database, you may need a easy way to count your elements. There's many ways of doing that, let's look at some various techniques...
  1. using '$increment'
  2. using '+'
  3. using the 'for' parameters
The '$increment' method:
logins() ;
    n i,c
    f  s i=$o(^users(i)) q:i=""  d
    . s c=$increment(c,1)
    q c

The '+' method:
logins() ;
    n i,c
    f  s i=$o(^users(i)) q:i=""  d
    . s c=c+1
    q c

The 'for' method:
logins() ;
    n i,c
    f c=0:1 s i=$o(^users(i)) q:i=""
    q c

For me the best is the 'for' method because you can do other thing in the loop too. For example let's 'write' the counter:
GTM> f c=0:1 s i=$o(^users(i)) q:i=""  w c,!
0
1
2
3
..
58
59


Finally, look at this and train your brain to think in the GTM way:
add2(values,count)     ; w $$add2^test(.values,.count)
    n sum
    n c
    n i
    f c=0:1 s i=$o(values(i)) q:i=""  d
    . w c,") ",i,!
    . s sum=sum+i
    s count=c
    q sum


Inside a shell you test it like this:
GTM> s values(1)=""
GTM> s values(2)=""
GTM> s values(3)=""
GTM> n count
GTM> w $$add2^test(.values,.count)
0) 1
1) 2
2) 3
6
GTM> w count
3

No comments:

Sticky