如何将条件逻辑添加到Oracle查询?

时间:2018-02-05 07:33:52

标签: oracle

我有一个Oracle查询:

SELECT
  TABLE1.function_id "functionID",
  TABLE1.function_file_name "function_file_name",
  NVL(TABLE1.parameters, '') "sParams",
  NVL(TABLE3.amount, 0) "function_amount",
  NVL(TABLE2.FREE, 0) "free",
  TABLE4.customer_id "customer_id",
  TABLE4.user_name "user_name"
FROM TABLE1
INNER JOIN TABLE2
  ON TABLE1.function_id = TABLE2.function_id
INNER JOIN TABLE4
  ON TABLE2.customer_user_id = TABLE4.customer_user_id
LEFT OUTER JOIN TABLE3
  ON TABLE3.function_id = TABLE1.function_id
  AND NVL(TABLE3.start_date, SYSDATE) <= SYSDATE
  AND NVL(TABLE3.end_date, SYSDATE) >= SYSDATE
WHERE function_name = 'Func1'
AND TABLE4.user_userid = 'TEST1'

将返回以下输出: enter image description here

我必须在这里添加条件逻辑。

如果上面的查询返回数据,那么我必须将查询结果设置为以下变量:

•   functionId 
•   functionFilename 
•   functionParams 
•   isFree 
•   chargeAmount   
•   customerId 
•   customerUserName

否则我必须返回错误。

我是Oracle新手。

1 个答案:

答案 0 :(得分:0)

您应该使用cursor。 查询示例:

declare 
  cursor cur1 is
SELECT
  TABLE1.function_id as "functionID",
  TABLE1.function_file_name as "function_file_name",
  NVL(TABLE1.parameters, '') as "sParams",
  NVL(TABLE3.amount, 0) as "function_amount",
  NVL(TABLE2.FREE, 0) as "free",
  TABLE4.customer_id as "customer_id",
  TABLE4.user_name as "user_name"
FROM TABLE1
INNER JOIN TABLE2
  ON TABLE1.function_id = TABLE2.function_id
INNER JOIN TABLE4
  ON TABLE2.customer_user_id = TABLE4.customer_user_id
LEFT OUTER JOIN TABLE3
  ON TABLE3.function_id = TABLE1.function_id
  AND NVL(TABLE3.start_date, SYSDATE) <= SYSDATE
  AND NVL(TABLE3.end_date, SYSDATE) >= SYSDATE
WHERE function_name = 'Func1'
AND TABLE4.user_userid = 'TEST1';
row1 cur1%rowtype;

begin
  OPEN cur1;
  FETCH cur1 INTO row1;
  CLOSE cur1;

  if row1.functionID is null then
    raise_application_error(-20001, 'Your Error!'); 
  end;
end;