SQL 状态:PostgreSQL 9.3 中的 42883

SQL state: 42883 in PostgreSQL 9.3

我有以下 table 称为 test_type,其中包含两列,即 colacolb

Table: test_type

create table test_type
(
    cola int,
    colb varchar(50)
);

现在我想创建一个具有相同列的类型。

类型type1

create type type1 as
(
cola int,
colb varchar(50)
);

我在这里创建了函数,我在其中传递类型名称 type1 以将数据插入到 table test_type.

--创建函数

create or replace function fun_test ( p_Type type1 )
returns void
as
$$
begin
    insert into test_type(cola,colb) 
    select cola,colb from p_type
    EXCEPT
    select cola,colb from test_type;
end
$$
language plpgsql;

---调用函数

SELECT fun_test(1,'Xyz');

错误详情:

ERROR: function fun_test(integer, unknown) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Character: 8

您需要 "pack" 将参数放在一起:(1,'xs'),以便 postgres 将它们识别为类型 1 的单个参数:

SELECT fun_test((1,'xs')); 

为了更好的可读性,您可以将参数转换为 type1(并非真正必要):

SELECT fun_test((1,'xs')::type1);

如果函数的目的是仅在 table 中未包含值时才插入值,您可以更改代码:

create or replace function fun_test ( p_Type type1 )
  returns void AS $$
BEGIN
    INSERT INTO test_type(cola,colb)
    SELECT p_Type.cola,p_Type.colb
    EXCEPT
    SELECT cola,colb FROM test_type;
END; 
$$ language plpgsql;

但我认为这种语法可读性不好。这个语句看起来更好:

...
BEGIN
  PERFORM 0 FROM test_type WHERE (cola, colb) = p_Type;
  IF NOT FOUND THEN
    INSERT INTO test_type(cola,colb) VALUES (p_Type.cola,p_Type.colb);
  END IF;
END;
...