如果您对随机有非常具体的定义,并且不允许重复,那么异常处理可以帮助避免重复。
这种方法会很慢。如果您需要多次执行此操作,或处理大量数据,您可能希望放宽对“随机”的定义,并使用 Erich 之类的解决方案。
--Create temporary unique constraint. (Assuming you want each column to be unique?)
alter table countries add constraint countries_name_uq unique (country_name);
--Insert random data until it worked 1 million times.
Declare
rows_inserted number := 0;
Begin
Loop
Begin
INSERT INTO COUNTRIES(COUNTRY_ID, COUNTRY_NAME)
VALUES(dbms_random.string('L', 7), dbms_random.string('L', 15));
--Only increment counter when no duplicate exception
rows_inserted := rows_inserted + 1;
Exception When DUP_VAL_ON_INDEX Then Null;
End;
exit when rows_inserted = 1000000;
End loop;
commit;
End;
/
--Drop the temporary constraint
alter table countries drop constraint countries_name_uq;
--Double-check the count of distinct rows
select count(*) from
(
select distinct country_id, country_name from countries
);
Result
------
1000000