我有2个表,Driver和Mechanic,在两个表中他们都有相同的列Employee#
如何使用PL / SQL检查两个表,以便通过比较员工#,在Driver表中的员工不会出现在Mechanic表中。如果它发生了,它会显示一条消息“员工#不能同时是司机和机械师!”
我知道我可以简单地比较两个表:
SELECT Employee#
FROM Driver
INTERSECT
SELECT Employee#
FROM Mechanic
但它要求我使用PL / SQL。
我尝试过使用光标,但我似乎无法让它贯穿整个列。这是我的代码:
declare
cursor c1 is select employee# from driver;
cursor c2 is select employee# from mechanic;
driverenum number(30);
mechanicenum number(30);
begin
open c1;
fetch c1 into driverenum;
close c1;
open c2;
fetch c2 into mechanicenum;
close c2;
if driverenum in (mechanicenum) then
dbms_output.put_line(driverenum);
end if;
end;
/
答案 0 :(得分:0)
如果唯一要求是您使用PL / SQL
DECLARE
TYPE emp_nt IS TABLE OF driver.employee#%type;
l_drivers emp_nt;
l_mechanics emp_nt;
l_both emp_nt;
BEGIN
SELECT employee#
BULK COLLECT INTO l_drivers
FROM driver;
SELECT employee#
BULK COLLECT INTO l_mechanics
FROM mechanic;
l_both := l_drivers MULTISET INTERSECT l_mechanics;
FOR i IN 1 .. l_both.count
LOOP
dbms_output.put_line( 'Employee ' || l_both(i) ||
' is employed as both a driver and a mechanic' );
END LOOP;
END;
如果两个表中都有大量行,则此方法可能会在PGA中占用相当大的空间。但通常它几乎和SQL解决方案一样有效。