在實際應用中,為了分頁或查詢效能的需要,我們往往需要從資料庫查詢固定行數的記錄,不同的資料庫有不同的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;
( 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;