sql - PL/SQL - Iterating over cursor and assigning value
问题描述
This may be a basic question, but I'm relatively new to PL/SQL and I'm stuck.
Let's say I have a cursor, for example:
cursor pr_cur(pr_id varchar2)
is
select priority
from some_table
where id = pr_id;
The priority column can have only 3 possible values: 'Low', 'High', 'Very high'
I want to iterate through the cursor and assign the highest priority found to a variable: max_pr.
for pr_rec in pr_cur(some_value)
loop
max_pr := pr_rec.priority;
exit when pr_rec.priority = 'Very high';
end loop;
I hope this is not a duplicate question. How should I go about doing this?
解决方案
您不需要Cursor 和不需要的循环if else
。您可以使用单个 sql 查询来获得最大优先级,使用适当ORDER BY
的 withrow_number
或FETCH FIRST
在Oracle 11g中
SELECT
priority
INTO max_pr
FROM
(
SELECT
t.*,
ROW_NUMBER() OVER(
ORDER BY
CASE priority
WHEN 'Very high' THEN 1
WHEN 'High' THEN 2
WHEN 'Low' THEN 3
ELSE 4
END
) AS rn
FROM
some_table t
)
WHERE
rn = 1;
Oracle 12c及更高版本
SELECT
priority
INTO max_pr
FROM
some_table t
ORDER BY
CASE priority
WHEN 'Very high' THEN 1
WHEN 'High' THEN 2
WHEN 'Low' THEN 3
ELSE 4
END
FETCH FIRST 1 ROWS ONLY
推荐阅读
- node.js - 为什么在 Windows 上通过 yarn 运行时,utf16 / 代理对表情符号无法在 console.log() 中正确显示?(直接npm和node都可以)
- sql-server - SQL Server 中的聚集索引:列在架构中的第一位有什么优势?
- android - Android布局是重叠元素
- wordpress - 如何从 Woocommerce 中的“我的帐户 > 订单”页面获取订单信息?$order->get_id() 与订单号不匹配
- angular - 引导轮播不工作在角度(10)
- javascript - 从嵌套数组中删除对象失败
- typeorm - 左连接和选择但不同
- javascript - 角材料不过滤选项
- elasticsearch - Elasticsearch - 使用字段匹配来提升而不是获取文档
- mongodb - 无法在 MongoDB GRAPHQL 查询中使用变量