作數據庫開發或管理的人常常要建立大量的測試數據,動不動就須要上萬條,若是一條一條的錄入,那會浪費大量的時間,本文介紹了Oracle中如何經過一條 SQL快速生成大量的測試數據的方法。
產生測試數據的SQL以下:
SQL> select rownum as id,
2 to_char(sysdate + rownum / 24 / 3600, 'yyyy-mm-dd hh24:mi:ss') as inc_datetime,
3 trunc(dbms_random.value(0, 100)) as random_id,
4 dbms_random.string('x', 20) random_string
5 from dual
6 connect by level <= 10;
ID INC_DATETIME RANDOM_ID RANDOM_STRING
---------- ------------------- ---------- --------------------------------------------------------------------------------
1 2009-12-08 19:43:14 76 GWMU280MIVBKKOCZV620
2 2009-12-08 19:43:15 34 GNV88O6TDHD3TWC5GWI5
3 2009-12-08 19:43:16 77 LI6H4O5IAHQIMO4B0WMH
4 2009-12-08 19:43:17 99 LP7XP49I0YOJIYSJDQZO
5 2009-12-08 19:43:18 55 V3284X9RXW4UZI8BQMO3
6 2009-12-08 19:43:19 16 T0OA52UAOGHL1TT46H25
7 2009-12-08 19:43:20 61 UY6RUOF7HWTO86942FLP
8 2009-12-08 19:43:21 25 JYXO4OPEW8J1CKVCPDJR
9 2009-12-08 19:43:22 10 DONU6W9QVQM3KJ2UG8LO
10 2009-12-08 19:43:23 76 J8DJLVNOUIZDXE4UXUJG
10 rows selected
上面SQL是利用了Oracle數據庫語法的幾個實用小技巧實現的:
一、利用Oracle特有的「connect by」樹形鏈接語法生成測試記錄,「level <= 10」表示要生成10記錄;
二、利用rownum虛擬列生成遞增的整數數據;
三、利用sysdate函數加一些簡單運算來生成日期數據,本例中是每條記錄的時間加1秒;
四、利用dbms_random.value函數生成隨機的數值型數據,本例中是生成0到100之間的隨機整數;
五、利用dbms_random.string函數生成隨機的字符型數據,本例中是生成長度爲20的隨機字符串,字符串中能夠包括字符或數字。
ok, 那要生成10萬條測試記錄表能夠用以下SQL:
create table myTestTable as
select rownum as id,
to_char(sysdate + rownum/24/3600, 'yyyy-mm-dd hh24:mi:ss') as inc_datetime,
trunc(dbms_random.value(0, 100)) as random_id,
dbms_random.string('x', 20) random_string
from dual
connect by level <= 100000;
本文來自 CSDN博客,轉載請標明出處:http://blog.csdn.net/yzsind/archive/2009/12/08 /4967133.aspx
======================================================================================
我的自用的語句:
insert into t_userbase
select userbase_seq_id.nextval, to_char(rownum+10),to_char(rownum+10),1 from dual connect by level <= 50000
本文來自 CSDN博客,轉載請標明出處: http://blog.csdn.net/Vange/archive/2010/06/24/5691077.aspxsql
- declare
- idss int :=10402;
- ids int :=11102;
- begin
- loop
- exit when ids>12884;
- insert into cp_org_owner(id,oo_org_id,oo_owner_id) values(idss,10000,ids);
- idsids:=ids+1;
- idssidss:=idss+1;
- end loop;
- commit; -- 提交一下
- end;
- declare
- maxrecords constant int := 100000;
- i int := 1;
- begin
- for i in 1..maxrecords loop
- insert into test2(id,name) values(test2_sql.nextval,to_char(9999+i));
- end loop;
- dbms_output.put_line('成功導入數據!');
- commit;
- end;
- create or replace procedure TestProc as
- begin
- for c in(select id,name from test2) loop
- insert into test(id,name) values(test2_seq.nextval,c.name);
- end loop;
- end;