postgresql - Return tuple and check for null -


i've got function:

create or replace function my_function(user_id bigint) returns bigint $body$ declare   var1 ???; --- ???  begin   --1   var1 := (select table1.field1, table2.field2     table1     inner join table2     -- ......   );    --2   --if var1 not null... 

first of all, want var1 tuple. have create type take it?

create type my_type .... 

which has 2 fields? or maybe there better way solve this?

secondly, want make sure var1 not null. how this?

you can create type or use type of existing table. use returns setof my_type.

but row type need in single function it's more convenient use returns table (...) - possibly in combination return query:

create or replace function my_function(user_id bigint)   returns table(field1 int, field2 text)  -- replace actual types! $func$ begin        return table    select t1.field1, t2.field2 -- table-qualify avoid naming conflict      table1 t1    join   table2 t2 on ...    ...  ;     -- if var1 not null ...    if not found       -- if nothing found, can ...       -- raise exception 'foo!' -- raise exception. or ...       -- return query select 1, 'foo'; -- return "default" row ...    end if; end $func$ language plpgsql; 

search key words in tag. there many examples.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -