【赛迪网-it技术报道】在实际的工作和学习中,为了分页或查询性能的需要,往往需要从数据库查询固定行数的记录,不同的数据库有不同的sql语句来完成,在oracle数据库中,我们可以用下面的方法来实现,假设要从一个有百万条记录的表中每次取10万条进行处理,可以按下面步骤进行:
1、创建表
drop table vehicle;
create table vehicle (
make varchar2(256) not null,
model varchar2(256),
registration_no number(15) not null primary key,
age number(2,1) not null,
category varchar(1) not null,
milage number(15,2) not null,
last_service_date date not null
);
2、插入数据
可以用入下存储过程进行批量数据的插入,
create or replace procedure insert_appointed_records
( startnum in number, endnum in number) as
i number:=startnum;
j number:=endnum;
begin
dbms_output.put_line(to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') );
while i<=j loop
insert into
vehicle (registration_no,make,model,age,category,milage,last_service_date)
values
(i,'test','test',3,'a',1000,sysdate);
i:=i+1;
end loop;
dbms_output.put_line(to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') );
end insert_appointed_records;
3、查询固定行数的记录
在oracle数据库中需要结合rownum来完成,可以用如下方法来实现,如要取按rowid排序的5000到10000之间的记录
select * from vehicle where rownum<10001 minus select * from vehicle where rownum<5001;
如果需要按照某字段排序来查询,如,按制造商make来排序,就需要用到子查询,性能就会有明显的影响
select * from (select * from vehicle order by make) where rownum<10001 minus select * from (select * from vehicle order by make) where rownum<5001;
由于你对rownum不能用像 where rownum >10 and rownum <100这样的语法,所以有点别扭,但是你可以通过以下方式来用:
select * from (select rownum r,registration_no,make,model,age,category,milage,last_service_date from vehicle) where r >=5000 and r<=10000;
或者
select * from (select rownum r,registration_no,make,model,age,category,milage,last_service_date from vehicle) where r between 5000 and 10000;
这样就比较合符习惯了,不能用如下语句:
select * from (select * from vehicle order by make) where rownum between 5000 and 10000;
或者
select * from (select * from vehicle order by make) where rownum >= 5000 and rownum<=10000;
闽公网安备 35060202000074号