我有一个表USERS
,其中有列username,fname, lname, age
。
我需要创建一个过程,如果年龄小于18,它将从参数中删除用户名。
我写了一些代码,但是没用:
create procedure delete_user(username in varchar2)
as
begin
if exists (delete from username where age < 18);
dmbs_output.put_line(username);
end;
exec detele_user('mrgreen');
答案 0 :(得分:3)
这是怎么回事。
首先测试用例:
SQL> create table users
2 (username varchar2(10),
3 age number);
Table created.
SQL> insert into users
2 select 'LF' , 10 from dual union all
3 select 'Marc', 20 from dual;
2 rows created.
程序:
SQL> create or replace procedure delete_user (p_username in varchar2)
2 is
3 begin
4 delete from users u
5 where u.username = p_username
6 and u.age < 18;
7
8 dbms_output.put_line('User ' || p_username ||
9 case when sql%rowcount = 0 then ' NOT ' end ||
10 ' deleted');
11 end;
12 /
Procedure created.
一些评论:
p_
sql%rowcount
的示例,该示例可帮助您了解受影响的行数最后,测试:
SQL> set serveroutput on;
SQL> exec delete_user('LF');
User LF deleted
PL/SQL procedure successfully completed.
SQL> exec delete_user('Marc');
User Marc NOT deleted
PL/SQL procedure successfully completed.
SQL>
与您的问题无关,但是-如果您发布实际编译的代码,通常会有所帮助。
dmbs_
无效delete_user
,则不要调用detele_user
答案 1 :(得分:1)
那么您基本上有3个选择。
1.在用户表中添加一列,指示“用户已被删除”。进行设置,但实际上不删除用户。
2.将子表上的FK修改为“ ON DELETE CASCADE”。 (如果DBA允许的话-很多/大多数都不会)。
3.修改程序以删除子行:以下是一种可能。
create or replace procedure delete_user (p_username in varchar2)
is
begin
delete from child_table c
where c.username = p_username
and exists (select null
from users u
where u.username = p_username
and u.age < 18
);
delete from users u
where u.username = p_username
and u.age < 18;
dbms_output.put_line('User ' || p_username ||
case when sql%rowcount = 0 then ' NOT ' end ||
' deleted');
end delete_user ;