Discussion Locked

SQL (DB2) row counts

0 helpful
14 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I need to determine the number of rows returned from a DB2 v6.1 Query in a CICS pgm - with the following caveats:
1. use a CURSOR (DECLARE, OPEN, FETCH, etc.)
2. make one SQL call - minimize I/O
3. NO dynamic SQL
4. NO stored procedures

This would be a no brainer in any other DB (SQL Server, Oracle et al.) yet DB2 does not appear to support a special register like %COUNT% ouside of using stored procedures. The have a GET STATISTICS command in stored procedures that returns the rows affected by the previous SQL statement.

Anyone have any thoughts on how to accomplish this ?
TIA

14 replies

by russell.gilbert

1) Use Select count(*) from myfile where ....
2) Try the same thing in a cursor
exec sql
delare mycursor cursor for
select var1, var2, count(*) from myfile
............
..........
end-exec.

Russell

by ds56748

This doesn't work in DB2 - already tried that. Gives a value of 1 in count(*) froeach returned row.

by russell.gilbert

1) Use Select count(*) from myfile where ....
2) Try the same thing in a cursor
exec sql
delare mycursor cursor for
select var1, var2, count(*) from myfile
............
..........
end-exec.

Russell

by russell.gilbert

1) Use Select count(*) from myfile where ....
2) Try the same thing in a cursor
exec sql
delare mycursor cursor for
select var1, var2, count(*) from myfile
............
..........
end-exec.

Russell

by ldelaprade

Have a Primary key ? If yes, look at this :
db2 => SELECT A.lProdId, A.Model from amProduct A

LPRODID MODEL
----------- --------------
23 -
25 Bundle
26 Asset1
27 Adjustment1
28 Adjustment2 29 Adjustment3
30 Asset2
31 Adjustment4
32 Adjustment5
33 Adjustment6
24 TOTO

11 record(s) selected.

Now examin the following variant :
db2 => SELECT A.lProdId, A.Model, COUNT(1) ASROWCOUNT from amProduct A, amProduct B WHERE B.lProdId

by ldelaprade

The best way will of course be provided by a DB2 function. This is available with DB2 UDB.
I don't know if it exists on DB2 OS390.

SELECT A.lProdId, A.Model, ROWNUMBER() OVER (ORDER BY lProdId) from amProduct A

by skurc

All the previous answers will work, but if you are limited to an "older" version of DB2, the follwing query structure will produce the same result as the one in which the table is joined to itself (using rowcount):

select count(col-1) as rows, col-1
from aTable
where ......
group by col-1 ;

You'll see results something like:

rows col-1
---- -----
3 ABC
1 DEF
4 GHI

Hope this also helps...

This discussion is closed to new replies.