intersystems-cacheintersystems-cache-studio

Display %ROWCOUNT value in a select statement


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        |
+----------+--------+---------+

Solution

  • 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 |
    +-----------+-------+-------------------+-----------+