oracle学习笔记_典型函数

**

–1.函数:根据员工号查询员工姓名 --IN可省略,是默认值

**

  CREATE or replace FUNCTION f_get_name(i_empno IN varchar2) 
  RETURN varchar2 IS
          i_ename emp.ename%TYPE;
  BEGIN
          SELECT ename INTO i_ename
          FROM emp
          WHERE empno = i_empno;
          return (i_ename);
  END;

–2.根据部门号查询部门名称,使用函数 查询人员姓名及部门名称

create or replace function f_get_name_by_deptno(t_deptno in varchar2)
return varchar2 is
v_dept_name dept.dname%type;
begin
select d.dname into v_dept_name
from dept d where d.deptno=t_deptno;
return v_dept_name;
select f_get_name_by_deptno('201') from emp

**

–3.传入一个员工编号,下属的人员姓名中间用,分隔

**

create or replace function f_lower_name(t_empno in number)
return varchar2 is
v_lower_name emp.ename%type;
begin 
select ename into v_lower_name
from emp where mgr=empno;
for c_lower_name in v_lower_name loop
return c_lower_name;
end loop;
dbms_output.put_line(''''||v_lower_name||''',');
end f_lower_name;

**

–4.创建函数 部门编号输入 返回部门下入职最早的前10名员工的姓名 --部门下一级的下一级人员 emp.deptno=dept.deptno emp_his.upperdeptno=dept.deptno

**

CREATE OR REPLACE FUNCTION get_twonames2(d_deptno IN dept.deptno%TYPE)
RETURN varchar2 IS
       CURSOR cv_names IS 
              SELECT ename FROM emp e,dept d1,dept d2
              WHERE d1.deptno = d_deptno AND d1.deptno = d2.upperdeptno AND (e.deptno = d1.deptno OR e.deptno = d2.deptno) 
              ORDER BY e.hiredate;
       tempval cv_names%ROWTYPE;
       e_names varchar2(100);
       indexval NUMBER;
BEGIN
  e_names := '';
  indexval := 1;  --在函数中采用数量限制
  FOR tempval IN cv_names
  LOOP
    exit when indexval > 10;
    e_names := e_names || ',' || tempval.ename;
    indexval := indexval+1;
  END LOOP;
  RETURN (e_names);
  END;

**

–5.根据传入的部门编号,返回一个字符串:返回这个部门下所有的人员姓名,中间用逗号分隔 --没有使用游标(若使用游标,与第3个函数类似)

**

  CREATE OR REPLACE FUNCTION get_names(i_deptno IN emp.deptno%TYPE)
  RETURN varchar2 IS
  -- 也可以定义一个游标来查多行数据(用游标更简单)
         i_names varchar2(200);  --声明变量时要求有长度
         temp emp.ename%TYPE;
         i_count NUMBER;
         i_index NUMBER;
  BEGIN
    SELECT COUNT(*) INTO i_count
    FROM emp
    WHERE deptno = i_deptno;
    i_index := 1;
    i_names := '';
    WHILE i_index <= i_count 
      LOOP
        SELECT ename INTO temp
        FROM (SELECT ename,rownum r FROM emp
              WHERE deptno = i_deptno
              ) 
        WHERE r = i_index;
        i_names:= i_names || ',' || temp;
        i_index := i_index + 1;
      END LOOP;
      RETURN (i_names);
  END;

你可能感兴趣的:(oracle学习笔记_典型函数)