I am trying to select only a certain number of records from a table.
It is easy enough with "fetch first" syntax. What complicates this a
bit is the fact that I need to retrieve the number of rows from another
table. So:
begin atomic
declare num_records int default 0;
set num_records = (select number_of_rows from master_table);
select * from main_table fetch first num_records rows only;
end
However, this does not seem to work as DB2 is expecting a literal
integer value in the "fetch first" clause. Is there a way around this?
Thanks in advance!
> I am trying to select only a certain number of records from a table.
> It is easy enough with "fetch first" syntax. What complicates this a
[quoted text clipped - 9 lines]
> However, this does not seem to work as DB2 is expecting a literal
> integer value in the "fetch first" clause. Is there a way around this?
How about this:
SELECT ...
FROM ( SELECT *, row_number() over() AS rn
FROM main_table ) AS t
WHERE t.rn BETWEEN 1 AND ( SELECT number_of_rows
FROM master_table )
Dynamic SQL would be another option.
p.s: Serge might have a more elegant solution. ;-)

Signature
Knut Stolze
Information Integration
IBM Germany / University of Jena
Serge Rielau - 08 Mar 2005 12:04 GMT
>>I am trying to select only a certain number of records from a table.
>>It is easy enough with "fetch first" syntax. What complicates this a
[quoted text clipped - 21 lines]
>
> p.s: Serge might have a more elegant solution. ;-)
This will do the trick. However it may scan main_table to completion.
Another option woudl be to throw the logic into a stored procedure and
use a dynamic cursor.
Cheers
Serge

Signature
Serge Rielau
DB2 SQL Compiler Development
IBM Toronto Lab