0

I am new to PostgreSQL. I have the query:

---------
DO
$$
DECLARE
    l_pin INT;
    l_pin1 int;
BEGIN
    l_pin := 3;
    l_pin1 := 4;

select l_pin,l_pin1;
END;
$$
LANGUAGE PLPGSQL;
--------------------------

from above query am getting an error as

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function inline_code_block line 9 at SQL statement
SQL state: 42601

I need to get the values of l_pin and l_pin1 as output.

2

2 Answers 2

1

What you have there is a DO statement, not a "query" nor a "function". DO statements cannot return anything at all.

The displayed error is because you cannot call SELECT in a plpgsql code block without assigning the result. To actually return values from a plpgsql function, use some form of RETURN (explicitly or implicitly). As minimal example:

CREATE OR REPLACE FUNCTION foo(OUT l_pin int, OUT l_pin1 int)
  RETURNS record AS  -- RETURNS record is optional because of OUT parameters
$func$
BEGIN
   l_pin := 3;
   l_pin1 := 4;

   RETURN;  -- RETURN is optional here because of OUT parameters
END
$func$  LANGUAGE plpgsql;

SELECT * FROM foo();

Related:

Sign up to request clarification or add additional context in comments.

Comments

0

First you can create a new type that can hold multiple values:

CREATE TYPE type_name AS (l_pin INTEGER, l_pin1 INTEGER);

Then you can do something like:

CREATE OR REPLACE FUNCTION function_name()
RETURNS type_name AS $$
  DECLARE
    result type_name;
  BEGIN
    /* Code that puts those values into type_name object 
    i.e. 
    result.l_pin := 3;
    result.l_pin1 := 4;
    */ 
    return result ;
  END
$$ language plpgsql

6 Comments

It could be done without creating additional type but using OUT parameters: CREATE OR REPLACE FUNCTION function_name(OUT l_pin INTEGER, OUT l_pin1 INTEGER) AS $$ .... For example: create function foo (out x int, out y int) language sql as $$ select 1, 2 $$;
@Abelisto You certainly can if you're on version 8.1+, but for me I prefer the creation of a type because it makes the code cleaner in my opinion.
Creating a type for this seems excessive. (And who would still be running Postgres older than version 8.1 - released in 2005?)
@ErwinBrandstetter It was for the sake of completeness, how does pointing out the version requirements for a feature hurt anything? Also, downvoting a correct answer because you think one line of code is excessive is poor form.
@BShaps: Granted, your answer works. So I removed the downvote. It's still bad advice IMO. And it's misleading to claim we'd need to create a new type.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.