2013-04-03 66 views
0

表的話,我想生成插入產生隨機的話從一個表插入到另一個表(PLSQL)

create table words 
(word varchar(100)); 

insert into words values ('Main street'); 
insert into words values ('Patrick Street'); 
insert into words values ('Red Street'); 
insert into words values ('Green street'); 
insert into words values ('Blue street'); 
insert into words values ('Yellow street'); 
insert into words values ('Silver street'); 
insert into words values ('Gold street'); 
insert into words values ('Brown street'); 

PLSQL代碼

declare 
randTemp number(10); 
tempCounty VARCHAR(20); 
streetaddress VARCHAR(100); 
Begin 
For i in 1..9 
Loop 
randTemp := dbms_random.value(1,5); 
SELECT c.countyname INTO tempCounty FROM county C WHERE c.countyid = randTemp; 
SELECT w.word INTO streetaddress FROM words w ORDER BY dbms_random.random limit 1; 
Insert into BRANCH values(i,streetaddress,tempCounty,randTemp); 
End loop; 
Commit; 
End; 
/

一切正常,除了這個select語句

SELECT w.word INTO streetaddress FROM words w ORDER BY dbms_random.random limit 1; 

我得到這個錯誤

ORA-06550:行10,列75: PL/SQL:ORA-00933:SQL命令不能正確地結束

我覺得限制可能是問題... ???

回答

1

你說得對,limit是問題,因爲這不是Oracle支持的東西。

你可以做這樣的事情,而不是:

SELECT word INTO streetaddress 
FROM (
    SELECT word 
    FROM words 
    ORDER BY dbms_random.random 
) 
WHERE rownum = 1; 

內部查詢是隨機排序的潛力的話,和出查詢使用rownum虛列挑選第一個返回值,類似於limit會做。

雖然在循環中重複該查詢似乎效率不高,你可能會更好做這樣的事情:

DECLARE 
    tempCounty VARCHAR(20); 
    streetaddress VARCHAR2(100); 
    cur sys_refcursor; 
BEGIN 
    OPEN cur FOR 
     SELECT word, countyname 
     FROM (
      SELECT w.word, c.countyname 
      FROM words w 
      CROSS JOIN county c 
      ORDER BY dbms_random.random 
     ) 
     WHERE rownum <= 9; 
    LOOP 
     FETCH cur INTO streetaddress, tempCounty; 
     EXIT WHEN cur%NOTFOUND; 
     dbms_output.put_line(streetaddress ||', '|| tempCounty); 
    END LOOP; 
END; 
/

也就是說,從生成兩個表中的字段,排序,以隨機,並把它限制爲前9個結果的所有可能的組合。

但是,這取決於你用什麼東西 - 如果你只是填充另一個問題所建議的表,那麼你可以使用這種查詢作爲insert into ... select ...構造的一部分,避免PL/SQL並完全循環:

INSERT INTO branch 
SELECT rownum, word, countyname, countyid 
FROM (
    SELECT w.word, c.countyname, c.countyid 
    FROM words w 
    CROSS JOIN county c 
    ORDER BY dbms_random.random 
) 
WHERE rownum <= 9; 

如果你在PL/SQL做更多的處理,有很多然後使用bulk collect可能會進一步加快速度行。

+0

雅這工作。感謝那:-) – Dtoon

+0

LIMIT在12c被引入,顯然。 –

相關問題