Oracle数据库中获取固定记录数的实用方法
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;