在數據庫中,有時候需要批量建立數據表進行測試,如果要建立的表太多,用直接用create table 的方式可能比較繁瑣,在這里寫了一個批量建立數據表的sql函數,以后批量建立就簡單了。
首先需要建立一個表空間用於專門存儲這些表的磁盤位置。
表空間:
-- Tablespace: post_data2 -- DROP TABLESPACE post_data2; CREATE TABLESPACE post_data2 OWNER postgres LOCATION 'F:\post_data2'; ALTER TABLESPACE post_data2 OWNER TO postgres;
建表函數:
-- FUNCTION: public.create_tables(integer) -- DROP FUNCTION public.create_tables(integer); CREATE OR REPLACE FUNCTION public.create_tables( table_num_in integer) RETURNS void LANGUAGE 'plpgsql' COST 100 VOLATILE AS $BODY$ declare v_table_num integer :=100; v_idx integer := 0; v_strTable varchar :=''; v_strSql varchar :=''; begin while v_idx < table_num_in loop v_idx = v_idx+1; v_strTable = CONCAT('table_', v_idx); v_strSql = 'create table '||v_strTable||'(idx integer,log varchar)WITH (OIDS = FALSE)TABLESPACE post_data2;'; EXECUTE v_strSql; end loop; end $BODY$; ALTER FUNCTION public.create_tables(integer) OWNER TO postgres;
函數使用
SELECT public.create_tables(100)
執行后會建立100個表
刪表函數:
-- FUNCTION: public.create_tables(integer) -- DROP FUNCTION public.create_tables(integer); CREATE OR REPLACE FUNCTION public.drop_tables( table_num_in integer) RETURNS void LANGUAGE 'plpgsql' COST 100 VOLATILE AS $BODY$ declare v_idx integer := 0; v_strTable varchar :=''; v_strSql varchar :=''; begin while v_idx < table_num_in loop v_idx = v_idx+1; v_strTable = CONCAT('table_', v_idx); v_strSql = 'drop table '||v_strTable; EXECUTE v_strSql; end loop; end $BODY$; ALTER FUNCTION public.drop_tables(integer) OWNER TO postgres;
SELECT public.drop_tables(100)
執行后會刪除之前建立的100張表
增加數據函數:
-- FUNCTION: public.create_tables(integer) -- DROP FUNCTION public.create_tables(integer); CREATE OR REPLACE FUNCTION public.add_tables_data( add_times_in integer, add_pert_in integer, table_num_in integer, text_len_in integer) RETURNS void LANGUAGE 'plpgsql' COST 100 VOLATILE AS $BODY$ declare v_idx integer := 0; v_idx_t integer := 0; v_strTable varchar :=''; v_strSql varchar :=''; begin while v_idx < add_times_in loop v_idx = v_idx+1; while v_idx_t < table_num_in loop v_idx_t = v_idx_t+1; v_strTable = CONCAT('table_', v_idx_t); v_strSql = 'insert into '||v_strTable||'(idx,log) select sn,repeat(''a'','||text_len_in||') from generate_series(0,'||add_pert_in||',1) as sn;'; EXECUTE v_strSql; end loop; end loop; end $BODY$; ALTER FUNCTION public.add_tables_data(integer,integer,integer,integer) OWNER TO postgres;
執行如下語句,就會對100個表,進行100批次數據插入,每次每個表插入10行記錄,每條記錄長200字節
SELECT public.add_tables_data(
100,
10,
100,
200
)
備注:
我這里選擇
LANGUAGE 'plpgsql'
是為了可以進行調試,如果使用sql的話,postgresql好像不支持調試,有興趣的可以試一下