格式化间隔日期类型作为 PostgreSQL 函数中的参数
Format interval date type as a parameter in PostgreSQL function
在 PostgreSQL 函数中参数化间隔日期类型的最佳方法是什么?。我有以下功能
CREATE OR REPLACE FUNCTION testing(
min_time integer
)
RETURNS void AS
$BODY$
BEGIN
EXECUTE format('CREATE TABLE foo AS
SELECT
gid,
now() + concat(%s, ' hours')::interval as x,
FROM foobar
limit 3 ',min_time );
END;
$BODY$
LANGUAGE plpgsql;
每次我尝试执行该函数时,我都会收到以下错误ERROR: syntax error at or near "hours"
单引号必须在字符串中转义:
CREATE OR REPLACE FUNCTION testing(min_time integer) RETURNS void
LANGUAGE plpgsql AS
$BODY$
BEGIN
EXECUTE format(
'CREATE TABLE foo AS
SELECT gid,
now() + ''%s hours''::interval as x
FROM foobar
limit 3',
min_time
);
END;
$BODY$;
但实际上,您不需要为此使用动态 SQL,静态 SQL 可能是更好的选择:
CREATE OR REPLACE FUNCTION testing(min_time integer) RETURNS void
LANGUAGE plpgsql AS
$BODY$
BEGIN
CREATE TABLE foo (
gid bigint NOT NULL,
x timestamp with time zone NOT NULL
);
INSERT INTO foo
SELECT gid,
now() + min_time * '1 hour'::interval
FROM foobar
limit 3;
END;
$BODY$;
在 PostgreSQL 函数中参数化间隔日期类型的最佳方法是什么?。我有以下功能
CREATE OR REPLACE FUNCTION testing(
min_time integer
)
RETURNS void AS
$BODY$
BEGIN
EXECUTE format('CREATE TABLE foo AS
SELECT
gid,
now() + concat(%s, ' hours')::interval as x,
FROM foobar
limit 3 ',min_time );
END;
$BODY$
LANGUAGE plpgsql;
每次我尝试执行该函数时,我都会收到以下错误ERROR: syntax error at or near "hours"
单引号必须在字符串中转义:
CREATE OR REPLACE FUNCTION testing(min_time integer) RETURNS void
LANGUAGE plpgsql AS
$BODY$
BEGIN
EXECUTE format(
'CREATE TABLE foo AS
SELECT gid,
now() + ''%s hours''::interval as x
FROM foobar
limit 3',
min_time
);
END;
$BODY$;
但实际上,您不需要为此使用动态 SQL,静态 SQL 可能是更好的选择:
CREATE OR REPLACE FUNCTION testing(min_time integer) RETURNS void
LANGUAGE plpgsql AS
$BODY$
BEGIN
CREATE TABLE foo (
gid bigint NOT NULL,
x timestamp with time zone NOT NULL
);
INSERT INTO foo
SELECT gid,
now() + min_time * '1 hour'::interval
FROM foobar
limit 3;
END;
$BODY$;