0

我要生成的带有单词的表

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 命令未正确结束

我认为限制可能是问题......?

4

1 回答 1

1

你是对的,limit这是问题所在,因为这不是 Oracle 支持的。

你可以这样做:

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

内部查询随机排序潜在的单词,而 out 查询使用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可能会进一步加快速度。

于 2013-04-03T11:23:59.727 回答