PostgreSQL表的测试数据

时间:2016-04-07 08:03:31

标签: sql postgresql postgresql-9.3

如何使用一个SQL查询在PostgreSQL表中创建测试数据?例如,我想在此表中插入几行数据:

PHAssetCollectionSubtypeSmartAlbumsynched

我测试了这段代码

CREATE TABLE RELEASE_PLANNING(
 ID INTEGER NOT NULL,
 NAME TEXT,
 PLANNING_START_DATE DATE,
 PLANNING_END_DATE DATE,
 DESCRIPTION TEXT,
 LAST_UPDATE DATE,
 CREATED DATE
)
;

我收到错误

org.postgresql.util.PSQLException:错误:INSERT的表达式多于目标列   职位:7

1 个答案:

答案 0 :(得分:2)

The error message correctly tells you that you're trying to insert three columns of data (?, generate_series(1,1000), md5(random()::text))) into two columns (INSERT INTO KNOWLEDGEBASE (ID, NAME)). It's not clear what this has to do with your create table statement, which creates a table of a different name, having seven columns.

This kind of query will insert 100 rows.

insert into release_planning
select n, 'a', current_date, current_date, 'a', current_date, current_date
from generate_series (1, 100) n;

If you want random data, the best approach is probably to write some functions, and use them in the select clause of that statement. So, I might write

  • random_integer(low, high),
  • random_date(low, high), and
  • random_string(length),

and call them like this.

insert into release_planning
select n, 
       random_string(35), 
       current_date, 
       random_date(current_date, date '2016-12-31'), 
       random_string(20), 
       random_date(date (current_date + interval '3 days'), date '2016-12-31'), 
       current_date
from generate_series (1, 100) n;