Display %ROWCOUNT value in a select statement

835 views Asked by At

How is the result of %ROWCOUNT displayed in the SQL statement.

Example

Select top 10 * from myTable.

I would like the results to have a rowCount for each row returned in the result set

Ex

+----------+--------+---------+
|rowNumber |Column1 |Column2  |
+----------+--------+---------+
|1         |A       |B        |
|2         |C       |D        |
+----------+--------+---------+
2

There are 2 answers

0
DAiMor On BEST ANSWER

There are no any simple way to do it. You can add Sql Procedure with this functionality and use it in your SQL statements. For example, class:

Class Sample.Utils Extends %RegisteredObject
{

ClassMethod RowNumber(Args...) As %Integer [ SqlProc, SqlName = "ROW_NUMBER" ]
{
  quit $increment(%rownumber)
}

}

and then, you can use it in this way:

SELECT TOP 10 Sample.ROW_NUMBER(id) rowNumber, id,name,dob 
FROM sample.person 
ORDER BY ID desc

You will get something like below

+-----------+-------+-------------------+-----------+
|rowNumber  |ID     |Name               |DOB        |
+-----------+-------+-------------------+-----------+
|1          |200    |Quigley,Neil I.    |12/25/1999 |
|2          |199    |Zevon,Imelda U.    |04/22/1955 |
|3          |198    |O'Brien,Frances I. |12/03/1944 |
|4          |197    |Avery,Bart K.      |08/20/1933 |
|5          |196    |Ingleman,Angelo F. |04/14/1958 |
|6          |195    |Quilty,Frances O.  |09/12/2012 |
|7          |194    |Avery,Susan N.     |05/09/1935 |
|8          |193    |Hanson,Violet L.   |05/01/1973 |
|9          |192    |Zemaitis,Andrew H. |03/07/1924 |
|10         |191    |Presley,Liza N.    |12/27/1978 |
+-----------+-------+-------------------+-----------+
0
Brendan Bannon On

If you are willing to rewrite your query then you can use a view counter to do what you are looking for. Here is a link to the docs.

The short version is you move your query into a FROM clause sub query and use the special field %vid.

SELECT v.%vid AS Row_Counter, Name 
  FROM (SELECT TOP 10 Name FROM Sample.Person ORDER BY Name) v 

Row_Counter Name
1           Adam,Thelma P.
2           Adam,Usha J.
3           Adams,Milhouse A.
4           Allen,Xavier O.
5           Avery,James R.
6           Avery,Kyra G.
7           Bach,Ted J.
8           Bachman,Brian R.
9           Basile,Angelo T.
10          Basile,Chad L.