我的下表名为test_type
,其中包含两列cola
和colb
。
表:test_type
create table test_type
(
cola int,
colb varchar(50)
);
现在我想创建一个具有相同列的类型。
输入:type1
create type type1 as
(
cola int,
colb varchar(50)
);
这里我创建了一个函数,我在其中传递类型名type1
以将数据插入到
表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
答案 0 :(得分:2)
你需要"打包"参数:(1,'xs')
,以便postgres将它们识别为type1的单个参数:
SELECT fun_test((1,'xs'));
为了更好的可读性,您可以将参数强制转换为type1(不是必需的):
SELECT fun_test((1,'xs')::type1);
如果函数的目的是仅在表中尚未包含值时插入值,则可以更改代码:
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;
...