首页 > 解决方案 > 在 PL/SQL 中连接两个表并获得所需的结果

问题描述

数据库中两个表的结构如下。

1) 部门表:Dept_Id number(5) 主键,Sept_Name varchar2(20),Employee_strength number(4) 不为空。

2)Employee 表:E_Id number(5), E_Name varchar2(20), Designation varchar2(20), D_ID number(5) 参考Department 表Dept_ID。

将写入一个 pl/sql 程序块来打印具有指定为“SE”的员工的部门的名称,如果在部门表中没有找到满足给定条件的记录,则代码应打印消息“未找到记录”如果记录发现代码必须打印部门名称。

请帮忙。

标签: plsql

解决方案


这是一个选项(基于类似于您的表格;这些属于 Scott)。

我会找一个推销员

SQL> break on deptno
SQL> select distinct d.deptno, e.job
  2  from dept d left join emp e on e.deptno = d.deptno
  3  order by d.deptno, e.job;

    DEPTNO JOB
---------- ---------
        10 CLERK
           MANAGER
           PRESIDENT
        20 ANALYST
           CLERK
           MANAGER
        30 CLERK
           MANAGER
           SALESMAN        --> only department 30 has SALESMEN
        40

10 rows selected.

SQL>

PL/SQL 块:

SQL> set serveroutput on
SQL> declare
  2    l_exists number(1);
  3  begin
  4    for cur_d in (select d.deptno, d.dname from dept d order by d.deptno) loop
  5      select max(1)
  6        into l_exists
  7        from emp e
  8        where e.deptno = cur_d.deptno
  9          and e.job = 'SALESMAN';
 10
 11      dbms_output.put_line(cur_d.deptno || ' - ' ||
 12                           case when l_exists = 1 then cur_d.dname
 13                                else  'no record found'
 14                           end);
 15    end loop;
 16  end;
 17  /
10 - no record found
20 - no record found
30 - SALES
40 - no record found

PL/SQL procedure successfully completed.

SQL>

推荐阅读