带有我要生成的单词的表
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 w.word INTO streetaddress FROM words w ORDER BY dbms_random.random limit 1;
我收到此错误
ORA-06550:第10行,第75栏: PL / SQL:ORA-00933:SQL命令未正确结束
我认为限制可能是问题...... ???
答案 0 :(得分: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
可能会进一步加快速度。