首页 > 解决方案 > PL/SQL:如何从多个表中删除行

问题描述

您好,我是 PL/SQL 的新手,我想编写一个从多个表中删除一个国家/地区的过程,它没有编译,我不知道该怎么做

由于有多个表,我应该输入哪些参数?如果名称是某些表中的主键,如何按名称删除国家/地区?

这些表是

NRiver   |   NameC
-------------------
Nile     |  Egypt

边界

NameC    |    NameB            |  Lenght
------------------------------------------
Canada   |    United States     |  76483

定位

NMountain  | NameC
------------------
1          | Canada

这是代码

Create or replace procedure DELETECOUNTRY (
        pname country.name%type) as

begin

delete from country where name=pname;
commit;
             dbms_output.put_line('Country deleted:' || ' '|| pnom );

delete from border where name=pname;
commit;
             dbms_output.put_line('Country deleted:' || ' '|| pnom );

delete from cross where name=pname;
commit;
             dbms_output.put_line('Country deleted:' || ' '|| pnom );

delete from locate where name=pname;
commit;
             dbms_output.put_line('Country deleted:' || ' '|| pnom );

EXCEPTION 
 
        when NO_DATA_FOUND then
            dbms_output.put_line('this country doesnt exist');

END;
/

谢谢

标签: sqloracleplsqlsql-delete

解决方案


你的问题有很多未知的东西:

  • 正如我已经要求添加 Oracle 标记。

  • 还添加一些示例数据和预期结果。

  • 此外,您在参数中有 pname,但您打印出 pnom:

     dbms_output.put_line('Country deleted:' || ' '|| pnom );
    

这是一个演示,当您更正 pnom 时,代码显示一切正常。如果问题出在其他地方,请检查前两个请求:

演示

这是您可以尝试欺骗主键值的一种选择:

create procedure DELETE_COUN (pname varchar) 
AS

  pnum1 int;
  pnum2 int;
  err_num NUMBER;
  err_msg VARCHAR2(100);
  
begin

pnum1 := 0;
pnum2 := 0;

LOOP

  begin
    delete from country 
    where name = pname;

    commit;
    
    pnum1 := 0;
    
  EXCEPTION 
    when others then
      err_num := SQLCODE;
      DBMS_OUTPUT.PUT_LINE(err_num);
      if err_num = '-2292' then
        pnum1 := pnum1 - 1;
      else
        raise_application_error(-20001,'Deleting data from table country was not succesful!');
      end if;
  end;
  
  begin
    delete from border 
    where name = pname;

    commit;

    pnum2 := 0;
    
  EXCEPTION 
    when others then
      err_num := SQLCODE;
      if err_num = '-2292' then
        pnum2 := pnum2 -1;
      else
        raise_application_error(-20001,'Deleting data from table border was not succesful!');
      end if;  
  end;
    
  EXIT WHEN pnum1 = 0 and pnum2 = 0;

END LOOP;

            
END;
/

这是一个演示:

演示


推荐阅读