[英]how do I pass a user defined type variable to a function as a parameter?
I want to pass a user defined type parameter to a PLPGSQL function, but I am getting this error at runtime:我想将用户定义的类型参数传递给 PLPGSQL 函数,但在运行时出现此错误:
dev=# select process_shapes();
ERROR: invalid input syntax for integer: "(,,7)"
CONTEXT: PL/pgSQL function process_shapes() line 9 at SQL statement
dev=#
For some reason, the parameters are not passed correctly and I have no idea why it doesn't work.出于某种原因,参数没有正确传递,我不知道为什么它不起作用。
My functions are:我的职能是:
CREATE OR REPLACE FUNCTION join_shapes(first_shape shape_t,second_shape shape_t,OUT new_shape shape_t)
AS $$
DECLARE
BEGIN -- simplified join_shape()s function
new_shape.num_lines:=first_shape.num_lines+second_shape.num_lines;
END;
$$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION process_shapes()
RETURNS void AS $$
DECLARE
rectangle shape_t;
triangle shape_t;
produced_shape shape_t;
BEGIN
rectangle.num_lines:=4;
triangle.num_lines:=3;
SELECT join_shapes(rectangle,triangle) INTO produced_shape;
RAISE NOTICE 'produced shape = %s',produced_shape;
END;
$$ LANGUAGE PLPGSQL;
Type definition:类型定义:
CREATE TYPE shape_t AS (
shape_id integer,
shape_name varchar,
num_lines integer
);
Postgres version: 9.6.1 Postgres 版本:9.6.1
When the target of a SELECT ... INTO
statement is of a composite type, it will assign each of the columns returned by the SELECT
to a different field in the target.当
SELECT ... INTO
语句的目标是复合类型时,它将把SELECT
返回的每一列分配给目标中的不同字段。
However, SELECT join_shapes(rectangle,triangle)
returns a single column of type shape_t
, and it's trying to cram the whole thing into the first column of the target, ie produced_shape.shape_id
(hence the error message about a failed integer conversion).但是,
SELECT join_shapes(rectangle,triangle)
返回shape_t
类型的单个列,并且它试图将整个内容塞入目标的第一列,即produced_shape.shape_id
(因此有关整数转换失败的错误消息)。
Instead, you need a SELECT
statement which returns three columns.相反,您需要一个返回三列的
SELECT
语句。 Just replace只需更换
SELECT join_shapes(rectangle,triangle)
with和
SELECT * FROM join_shapes(rectangle,triangle)
Alternatively, you could use或者,您可以使用
produced_shape := (SELECT join_shapes(rectangle,triangle));
which performs a single assignment, rather than trying to assign the target fields individually.它执行单个分配,而不是尝试单独分配目标字段。
For other people whom want to pass composite types to functions:对于想要将复合类型传递给函数的其他人:
create type pref_public.create_test_row_input as (
name text
);
create or replace function pref_public.create_test_row(test_row pref_public.create_test_row_input) returns pref_public.test_rows as $$
insert into pref_public.test_rows (name)
values
(test_row.name)
returning *;
$$ language sql strict security definer;
grant execute on function pref_public.create_test_row to pref_user;
You'll need to use row()
您需要使用
row()
select * from pref_public.create_test_row(row('new row'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.