Question

I've got a function:

CREATE OR REPLACE FUNCTION my_function(user_id BIGINT) RETURNS BIGINT AS
$BODY$
DECLARE
  var1 ???; --- ???

BEGIN
  --1
  var1 := (SELECT table1.field1, table2.field2
    FROM table1
    INNER JOIN table2
    -- ......
  );

  --2
  --if var1 is not null...

First of all, I want var1 to be a tuple. I have to create a type like this I take it?

CREATE TYPE my_type ....

which has two fields? Or maybe there is a better way to solve this?

Secondly, I want to make sure var1 is not null. How could do this?

Was it helpful?

Solution

You can create a TYPE or use the type of an existing table. Then use RETURNS SETOF my_type.

But for a row type you only need in a single function it's more convenient to just use RETURNS TABLE (...) - possibly in combination with RETURN QUERY:

CREATE OR REPLACE FUNCTION my_function(user_id bigint)
  RETURNS TABLE(field1 int, field2 text) AS  -- replace with actual types!
$func$
BEGIN    
   RETURN TABLE
   SELECT t1.field1, t2.field2 -- table-qualify to avoid naming conflict
   FROM   table1 t1
   JOIN   table2 t2 ON ...
   ...  ;

   -- if var1 is not null ...
   IF NOT FOUND THEN
      -- If nothing was found, you can ...
      -- RAISE EXCEPTION 'foo!' -- to raise an exception. Or ...
      -- RETURN QUERY SELECT 1, 'foo'; -- return a "default" row ...
   END IF;
END
$func$ LANGUAGE plpgsql;

Search for those key words in the tag. There are many examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top