在 PLSQL 函数中使用 NVL

Using NVL in PLSQL function

我创建了一个函数,它应该接受 employee_id 作为参数,以及 return 员工赚取的总薪水。如果佣金百分比为空,我应该在哪里放置 NVL 函数和 return 零?

CREATE OR REPLACE FUNCTION TOTAL_SAL (vemp IN employees.employee_id%type)
RETURN NUMBER
IS
    vsalary     employees.salary%type;
    vcommission employees.commission_pct%type;

    CURSOR c_employee IS
    SELECT SALARY 
      FROM employees
     WHERE employee_id = vemp;

BEGIN
    OPEN c_employee;
    FETCH c_employee INTO vsalary;
    CLOSE c_employee;

    vsalary := vsalary + vsalary * vcommission;

    RETURN vsalary;

END;
/

这就是您的使用方式。

cursor c_employee is
select NVL(SALARY, 0)
FROM employees
where employee_id = vemp;

有关更多 PLSQL 内容和其他内容,这是一个很好的资源:

https://www.techonthenet.com/oracle/functions/nvl.php

您可以选择任何一种风格;

  1. 在SQLSELECT语句内;

    CURSOR c_employee IS
    SELECT NVL(salary,0)
      FROM employees
     WHERE employee_id = vemp;
    

  1. 在PL/SQL代码块内

    vsalary := NVL(vsalary,0) + NVL(vsalary,0) * NVL(vcommission,0);
    

    vsalary := vsalary + vsalary * NVL(vcommission,0);
    

    前提是 NVL() 函数已经在 SELECT 语句中应用。

注意到 vcommission 比薪水更需要 NVL() 功能。

顺便说一句,好像你的意思是vemp作为参数,而employee_id是table

的列

为什么你认为你需要一个游标?如果您传递员工的 ID,则只能返回一(或 none)行,除非两个(或更多)员工共享相同的 ID,否则将是完全错误的。

因此,在我看来是这样的。

对于以下样本数据...

SQL> select * from employees where rownum <= 5;

EMPLOYEE_ID     SALARY COMMISSION_PCT
----------- ---------- --------------
       7369        800
       7499       1600              3
       7521       1250              5
       7566       2975
       7654       1250             14

... 函数计算总薪水(或 returns NULL 如果传递给它的 ID 无效):

SQL> create or replace function total_sal (vemp in employees.employee_id%type)
  2    return number
  3  is
  4    retval number;
  5  begin
  6    -- presuming everyone has initial salary, there's no need
  7    -- to apply NVL to SALARY column's value
  8    select salary * (1 + nvl(commission_pct, 0)/100)
  9      into retval
 10      from employees
 11      where employee_id = vemp;
 12    return retval;
 13  exception
 14    when no_data_found then
 15      return null;
 16  end;
 17  /

Function created.

我们来测试一下:

SQL> select e.*, total_sal(employee_id) total
  2  from employees e where rownum <= 5;

EMPLOYEE_ID     SALARY COMMISSION_PCT      TOTAL
----------- ---------- -------------- ----------
       7369        800                       800
       7499       1600              3       1648   --> 3% out of 1600 is 48, so total = 1600 + 48 = 1648
       7521       1250              5     1312,5
       7566       2975                      2975
       7654       1250             14       1425

SQL>

无效ID:

SQL> select total_sal(-1e99) total_sal from dual;

 TOTAL_SAL
----------


SQL>

我觉得不错。