我必须在表中插入时间戳值。我通过编写存储过程来插入值 这是我的存储过程的代码。
CREATE OR REPLACE FUNCTION dataInsert_Schedule() RETURNS boolean As
$$
DECLARE
i integer;
j integer;
dur integer;
tup Channel%rowtype;
BEGIN
FOR tup IN SELECT * FROM Channel
LOOP
for i in 0..6 LOOP --days
for j in 0..23 LOOP --hours
dur = round((random() * 2) + 1);
IF i + dur > 24 then
dur = 24 - i;
END IF;
INSERT INTO Schedule VALUES(tup.Channel_ID, round((random() * 999) + 1),( current_date + (integer to_char(i,'9')) )+ (interval to_char(j,'99') || ' hour'), (interval dur ||' hour'));
i = i + dur - 1;
END LOOP;
END LOOP;
END LOOP;
return true;
END
$$ LANGUAGE plpgsql;
当我编写查询Select * From dataInsert_Schedule();
时,我收到以下错误:
ERROR: syntax error at or near "to_char"
LINE 1: ...d((random() * 999) + 1),( current_date + (integer to_char( $...
^
QUERY: INSERT INTO Schedule VALUES( $1 , round((random() * 999) + 1),( current_date + (integer to_char( $2 ,'9')) )+ (interval to_char( $3 ,'99') || ' hour'), (interval $4 ||' hour'))
CONTEXT: SQL statement in PL/PgSQL function "datainsert_schedule" near line 15
********** Error **********
ERROR: syntax error at or near "to_char"
SQL state: 42601
Context: SQL statement in PL/PgSQL function "datainsert_schedule" near line 15
我首先尝试了这个
INSERT INTO Schedule VALUES(tup.Channel_ID, round((random() * 999) + 1),( current_date + (integer ''||i) )+ (interval (j ||' hour')), (interval dur ||' hour'));
插入方式,但我遇到了同样的错误。
为什么我收到此错误?
schedule
表定义如下:
CREATE TABLE Schedule(
Channel_ID Integer REFERENCES Channel(Channel_ID),
Program_ID Integer REFERENCES Program(Program_ID),
Start_Time Timestamp NOT NULL,
Duration Interval NOT NULL,
CONSTRAINT Schedule_Key PRIMARY KEY(Channel_ID, Program_ID)
);
答案 0 :(得分:1)
这对我有用:
select (to_char(1,'99') || ' hour')::interval;
您不需要to_char
:
select (1 || ' hour')::interval;
interval
----------
01:00:00
所以这就是它:
INSERT INTO Schedule
VALUES (
tup.Channel_ID,
round((random() * 999) + 1),
(current_date + i::integer) + (j || ' hour')::interval,
(dur ||' hour')::interval
)
答案 1 :(得分:0)
可以在字符串常量之前指定类型名称以将其强制转换为此类型,但它仅适用于常量。因此integer '123'
很好,但不允许integer to_char(something)
或interval column_name
,这就是您的查询失败的原因。
本手册的SQL语法章节对此进行了解释,特别是本段:Constants of Other Types 摘录:
可以使用任何一个输入任意类型的常量 以下注释:
输入'string'
“串” ::类型
CAST('字符串'AS类型)
及以下:
::,CAST()和函数调用语法也可用于指定 任意表达式的运行时类型转换
与问题相关的问题是type 'string'
符号未包含在可接受任意表达式的语法中,与::
和cast()
相反。