sql - 创建一个接受字符串并返回多行的函数
问题描述
我需要创建一个函数,该函数根据用户的输入转换单个列的值。我需要一些关于这样做的语法帮助。
这是我当前正在执行以获取行的查询:
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;
有人可以帮我创建这个函数的语法吗?
解决方案
像这样的东西
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');
这里有一个演示
推荐阅读
- c# - C#遍历调用相同函数的类
- java - 如何在 SQliteopenhelper 中更新项目位置
- apache-flink - 表选项不包含选项键“连接器”
- javascript - 如何在不重新渲染 react.js 中的先前消息的情况下渲染新消息?
- html - 我需要使用 CSS 合并垂直和水平文本,如附加的图像
- spring-boot - Spring Boot - 处理 CSV 以及 Excel 多部分文件
- sockets - 无法使用“sudo systemctl status apache2”
- spring-boot - 为什么OAuth2UserService在WebSecurityConfigurerAdapter下的Spring Boot中没有运行角色授权?
- javascript - 如何使用 sweetalert 在 html 中显示 php 警报消息
- java - 如何使用 Java 删除 CSV 文件中的重复列