5

I have the following function called as pro(). From which I want to return the strings by union all of two select statements and product output.

Function: pro()

My try:

create or replace function pro()
returns varchar as

$$

declare
    sql varchar;
    q varchar;
begin
    sql := 'SELECT DISTINCT  CAST(COUNT(ProductNumber) as varchar) ||'' - Count of the product Number '' as Descp
        FROM product
        UNION ALL
        SELECT DISTINCT CAST(COUNT(ProductName) AS varchar) || '' - Count of the product Name '' as Descp
        FROM product';

    raise info '%',sql;

    execute sql into q;

    return q;

end;
$$

language plpgsql;

Calling Function:

select pro();

This returning only the first part of select statement:

 ______________________________________
|pro                                   |
|character varying                     |
|______________________________________|
|6 - Count of the product Number       |
|______________________________________|

But the expected result should be:

 ______________________________________
|pro                                   |
|character varying                     |
|______________________________________|
|6 - Count of the product Number       |
|______________________________________|
|6 - Count of the product Name         |
|______________________________________|
0

1 Answer 1

7

Try use these functions :

using plpgsql

create or replace function pro1()returns 
table ( 
       descp text
      )
as
$$
begin
    return QUERY execute (
         'SELECT DISTINCT  CAST(COUNT(product) as varchar) ||'' - Count of the product Number '' as Descp
         FROM product
         UNION ALL
         SELECT DISTINCT CAST(COUNT(productid) AS varchar) || '' - Count of the product Name '' as Descp
         FROM product');
end;
$$
language plpgsql;

or

using sql

create or replace function pro2() returns table  ( descp text) 
as
$$
  SELECT DISTINCT  CAST(COUNT(product) as varchar) ||' - Count of the product Number ' as Descp
  FROM product
    UNION ALL
  SELECT DISTINCT CAST(COUNT(productid) AS varchar) || ' - Count of the product Name 'as Descp
  FROM product;
$$
language sql;
Sign up to request clarification or add additional context in comments.

2 Comments

Panther, Yeah! Got it. Thank you so much.
RETURN QUERY EXECUTE is not necessary, a simple RETURN QUERY should be enough, if there are no dynamic query parts -- also note, that such simple result can also be declared as RETURNS SETOF TEXT, but of course with RETURNS TABLE a column alias can be specified at function declaration level.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.