简体   繁体   中英

(PostgreSQL) How to create a function based on a text argument and return a list

I have a SELECT statement that returns a list:

SELECT  "db"."accounts"."account" as account
FROM db.accounts
WHERE db.accounts.level = 'Level 4' AND db.accounts.report = 'Report A'

As report can be either Report A or Report B, I want to create a function that the user chooses which report, something like: get_account('Report A').

What I've tried:

CREATE TYPE get_accounts_results AS ARRAY[];

CREATE OR REPLACE FUNCTION get_accounts(report TEXT) RETURNS get_accounts_results AS

    $$ 
        SELECT  "db"."accounts"."account" as account
        FROM db.accounts
        WHERE db.accounts.level = 'Level 4' AND db.accounts.report = $1
    $$

    LANGUAGE SQL;

SELECT get_accounts('Report A') AS report_account;

This gives me back 1 value only, when in fact I need n values - the quantity of values on this list is dynamic. Probably the type being created is wrong, but I didn't find anything that made sense in this scenario.

My question is: how to adjust this query in order to get the result of the created function on a list?

(PS: My end objective is to be able to iterate through this list to make a query that dynamically adds the query result to a materialized view)

You need to define your function to return a table. And you don't really need the type definition either:

CREATE OR REPLACE FUNCTION get_accounts(p_report TEXT) 
  RETURNS table(report_account text)
AS
$$ 
  SELECT act.account
  FROM db.accounts as act
  WHERE act.level = 'Level 4' 
    AND act.report = p_report;
$$
LANGUAGE SQL;

The above assumes that the column account is of type text . If it is not, then you need to adjust the data type in RETURNS table(report_account text) accordingly.

Then you can call it like this:

SELECT *
FROM get_accounts('Report A');

Unrelated, but: a column alias that is the same as the column name doesn't really make sense. "account" as account" is exactly the same thing as "account"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM