我想在下表中插入,但我无法转换日期的ARRAY。
CREATE TABLE schedule (
idschedule serial NOT NULL,
idzone integer NOT NULL,
"time" timestamp without time zone NOT NULL,
automatic boolean NOT NULL,
idrecurrence character varying(20),
duration integer,
date date,
)
我正在尝试执行的INSERT
:
INSERT INTO schedule(idzone, "date", "time", duration, automatic)
SELECT x, y, '20:00:00' id, '20', 'FALSE'
FROM unnest(ARRAY[3,4,5]) x, unnest( ARRAY[ 2015-4-12, 2015-4-19, 2015-4-26]) y
我收到以下错误:
错误:列'date'的类型为date但表达式的类型为integer
答案 0 :(得分:4)
array literal 甚至比array constructor更简单:
'{2015-4-12, 2015-4-19}'::date[]
如果你足够幸运地运行当前版本的Postgres 9.4(或更高版本),有一种新的安全方法可以并行取消两个阵列:
INSERT INTO schedule(idzone, "date", "time", duration, automatic)
SELECT x, y, '20:00:00' id, 20, FALSE
FROM unnest('{3,4,5}'::int[]
, '{2015-4-12,2015-4-19,2015-4-26}'::date[]
) AS t (x,y) -- produces 3 rows
详细说明:
除非你wanted
将一个数组的每个元素交叉连接到另一个数组的每个元素,否则产生9行的笛卡尔积。那么你的原始形式是正确的。
除此之外:从不使用保留字或基本类型名称(如" date"和"时间"作为标识符。
答案 1 :(得分:1)
正如错误消息所示,2015-4-12
不是日期。数字2015
减去数字4
减去数字12
。
您可以将个人日期写为:
'2014-04-12'::date
或
date '2015-4-12'
数组的较短形式(避免单独的演员表)将是:
ARRAY['2015-4-12', '2015-4-19']::date[]