postgresql - How to write a function that returns text or integer values? -
i'm using postgresql 9.2.4.
postgres=# select version();
version ------------------------------------------------------------- postgresql 9.2.4, compiled visual c++ build 1600, 64-bit (1 row)
my query executes insertion safely. need function should return except void datatype. text("inserted table") or integer(0-false,1-true) , useful me validate whether inserted or not?
i need syntax function returns integer
or text
when insertion done. validation purpose. there way solve this?
what need
most need 1 function return text
, 1 return integer
or function returns boolean
indicate success. of trivial , i'll refer excellent manual on create function
or code examples in similar questions on so.
what asked
how write function returns text or integer values?
... in sense have one return type being either text
or integer
. not trivial, not impossible has been suggested. key word is: polymorphic types.
building on simple table:
create table tbl( tbl_id int, txt text, nr int );
this function returns either integer or text (or other type if allow it), depending on input type.
create function f_insert_data(_id int, _data anyelement, out _result anyelement) returns anyelement $func$ begin case pg_typeof(_data) when 'text'::regtype insert tbl(tbl_id, txt) values(_id, _data) returning txt _result; when 'integer'::regtype insert tbl(tbl_id, nr) values(_id, _data) returning nr _result; else raise exception 'unexpected data type: %', pg_typeof(_data)::text; end case; end $func$ language plpgsql;
call:
select f_insert_data(1, 'foo'::text); -- explicit cast needed. select f_insert_data(1, 7);
simple case
one function returns true
/ false
indicate whether row has been inserted, 1 input parameter of varying type:
create function f_insert_data2(_id int, _data anyelement) returns boolean $func$ begin case pg_typeof(_data) when 'text'::regtype insert tbl(tbl_id, txt) values(_id, _data); when 'integer'::regtype insert tbl(tbl_id, nr) values(_id, _data); else raise exception 'unexpected data type: >>%<<', pg_typeof(_data)::text; end case; if found return true; else return false; end if; end $func$ language plpgsql;
the input type can replaced text
parameter purposes, can cast , other type.
Comments
Post a Comment