Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
Discussion Groups
Database Servers
DB2InformixIngresMS SQLOraclePervasive.SQLPostgreSQLProgressSybase
Desktop Databases
FileMakerFoxProMS AccessParadox
General
General DB TopicsDatabase Theory
Related Topics
Java Development.NET DevelopmentVB DevelopmentMore Topics ...

Database Forum / DB2 Topics / March 2005

Tip: Looking for answers? Try searching our database.

Fetch first

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
deebeetwo@yahoo.com - 08 Mar 2005 04:05 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
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!
Knut Stolze - 08 Mar 2005 07:11 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 - 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

 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.