【发布时间】:2020-10-13 13:52:44
【问题描述】:
在 Oracle DB (12) 中,我有 2 个表:
表格:STEP_DETAILS
+-----------+---------+---------------+
| record_id | step_id | material_type |
+===========+=========+===============+
| 1 | 1 | in |
+-----------+---------+---------------+
| 2 | 1 | in |
+-----------+---------+---------------+
| 3 | 1 | out |
+-----------+---------+---------------+
| 4 | 2 | in |
+-----------+---------+---------------+
| 5 | 2 | out |
+-----------+---------+---------------+
| 6 | 2 | out |
+-----------+---------+---------------+
表:ACTIONS_DETAILS
+-----------+-----------+---------------+
| record_id | action_id | material_type |
+===========+===========+===============+
| 1 | 11 | in |
+-----------+-----------+---------------+
| 2 | 11 | out |
+-----------+-----------+---------------+
| 3 | 12 | in |
+-----------+-----------+---------------+
| 4 | 12 | out |
+-----------+-----------+---------------+
所有 id 列都是 INTEGER 类型。
我需要计算两个表的输入材料。 在 PL/SQL 块中,我有以下函数,每个函数都有“几乎”相同的查询:
--count from step_details:
FUNCTION get_step_input_count(p_step_id step_details.step_id%TYPE)
RETURN INTEGER
IS
l_count INTEGER := 0;
BEGIN
SELECT COUNT(1)
INTO l_count
FROM step_details
WHERE step_id = p_step_id
AND material_type = 'in';
RETURN l_count;
END get_step_input_count;
--count from action_details:
FUNCTION get_action_input_count(p_action_id action_details.action_id%TYPE)
RETURN INTEGER
IS
l_count INTEGER := 0;
BEGIN
SELECT COUNT(1)
INTO l_count
FROM action_details
WHERE action_id = p_action_id
AND material_type = 'in';
RETURN l_count;
END get_action_input_count;
是否可以编写一个单独的 SELECT 语句,每次可以根据某些条件查询 2 个表之一,所以我最终将编写一个使用一个查询而不是 2 个函数的函数,例如:
FUNCTION get_input_count(p_parent_id integer,
p_from varchar2)
RETURN INTEGER
IS
l_count INTEGER := 0;
BEGIN
SELECT COUNT(1)
INTO l_count
FROM (when p_from = 'S' then 'step_details'
when p_from = 'A' then 'action_details')
WHERE (when p_from = 'S' then 'step_id = p_parent_id'
when p_from = 'A' then 'action_id = p_parent_id')
AND material_type = 'in';
RETURN l_count;
END get_input_count;
【问题讨论】:
标签: sql oracle plsql stored-functions