简体   繁体   中英

Passing user-defined Type Array as input parameter to a function

I have created a user-defined type in PostgreSQL(version 11.5).

CREATE TYPE key_type AS (key_no character varying(50), key_nm character varying(128));

I created below function with an input parameter of type key_type[] and output as TEXT .

create or replace function fn_net(inp IN key_type[]) returns TEXT as........

But I am unable to call the function, I have tried as below.

do  
$$  
declare  
v_key key_type[];  
v_res TEXT;  
begin  
v_key.key_no := '709R';  
v_key.key_nm := 'Risk';  
select * from fn_det(v_key) into v_res;  
raise notice '%', v_res;  
end;  
$$  
language plpgsql;

I get malformed array error or function does not exist error. Please help me as to how to pass the inputs correctly.

NOTE: I am able to run successfully if I specify input type as key_type instead of key_type[] but I need array type for the requirement.

Your variable assignment is wrong, you need to provide the array index to which you want to assign an element.

When you are calling a function returning a single value, you don't need a SELECT in PL/pgSQL, just assign the result:

do  
$$  
declare  
  v_key key_type[];  
  v_res TEXT;  
begin  
  v_key[1] := ('709R', 'Risk'); -- first array element
  v_key[2] := ('711X', 'Risk2'); -- second array element
  v_res := fn_det(v_key);  
  raise notice '%', v_res;  
end;  
$$  
language plpgsql;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM