首页 > 解决方案 > 创建一个接受字符串并返回多行的函数

问题描述

我需要创建一个函数,该函数根据用户的输入转换单个列的值。我需要一些关于这样做的语法帮助。

这是我当前正在执行以获取行的查询:

SELECT payment_id, rental_id, amount FROM payment

在此处输入图像描述

关于我正在尝试做的一些伪代码:

function getReport(String currencyType){
    if(currencyType == 'EUR'){

       Multiply the values in the amounts column by 1.16 and append Euros to it
       Return all the rows in the table

    }else if(currencyType == 'RMB'){

       Multiple the values in the amounts column by 6.44 and append RMB to it
       Return all the rows in the table

    }else{

       Do nothing because the default column values are in USD
       Return all the rows in the table

    }
}

我一直在尝试创建一个,但我在语法上苦苦挣扎。
不工作:

CREATE OR REPLACE FUNCTION get_data(currency_type text) RETURNS TABLE payment_info AS $$
    CASE currency_type
    WHEN 'EUR' THEN
        SELECT payment_id, rental_id, amount * 1.16 FROM payment;
    WHEN 'RMB' THEN
        SELECT payment_id, rental_id, amount * 6.44 FROM payment;
    WHEN 'USD' THEN
        SELECT payment_id, rental_id, amount FROM payment;
$$ LANGUAGE SQL;

有人可以帮我创建这个函数的语法吗?

标签: sqlpostgresqlfunctionset-returning-functionscreate-function

解决方案


像这样的东西

CREATE OR REPLACE FUNCTION get_data(currency_type text) 
RETURNS TABLE  ( payment_id int, rental_id int, amount numeric(5,2) ) 
language plpgsql
as $$
begin 
   return query 
     SELECT b.payment_id, b.rental_id, 
    case 
        when currency_type = 'EUR' then b.amount * 1.16     
        when currency_type = 'RMB' then b.amount * 6.44 
        when currency_type = 'USD' then b.amount 
    end as amount 
    FROM payment b;
end;$$

如果您使用,它确实以表格的形式返回

select * from get_data('EUR');

这里有一个演示

db<>fiddle 中的演示


推荐阅读