pl / sql处理重复

时间:2015-03-21 10:40:51

标签: sql database plsql

你好我必须制作插入新行的程序,并在表中存在其他工人具有相同姓氏时进行回滚。

我在网上查了一下,但是找不到具体的信息。我必须使用异常dup_val_on_index

create or replace PROCEDURE insert_date(
   p_id IN WORKERS.ID%TYPE,
   p_PESEL IN WORKERS.PESEL%TYPE,
   p_name IN WORKERS.NAME%TYPE,
   p_surname IN WORKERS.SURNAME%TYPE,
   p_date_birth IN WORKERS.DATE_BIRTH%TYPE,
   p_salary IN WORKERS.SALARY%TYPE)
IS
BEGIN

INSERT INTO WORKERS VALUES (p_id, p_PESEL,p_name,p_surname, p_date_birth,p_salary);

COMMIT;
EXCEPTION
   when DUP_VAL_ON_INDEX then
   dbms_output.put_line('DUP_VAL_ON_INDEX exception.');
    ROLLBACK;
END;

BEGIN
insert_date(5,92060111111,'wikta','dss',TO_DATE('2003/07/10',    'yyyy/mm/dd'),100);
END;

2 个答案:

答案 0 :(得分:1)

您只需要检查表中是否已存在SURNAME。如果不存在,则可以插入并提交行。试试这个:

create PROCEDURE insert_date(
p_id IN WORKERS.ID%TYPE,
p_PESEL IN WORKERS.PESEL%TYPE,
p_name IN WORKERS.NAME%TYPE,
p_surname IN WORKERS.SURNAME%TYPE,
p_date_birth IN WORKERS.DATE_BIRTH%TYPE,
p_salary IN WORKERS.SALARY%TYPE)

IS 
  varTmp NUMBER:=0;
BEGIN
-- check here whether the surname already exist or not
SELECT decode((select max(t.d) from (SELECT 1 d FROM WORKERS WHERE SURNAME = p_surname) t),1, 2) INTO varTmp FROM dual;

-- insert
IF (varTmp <> 2) THEN
    INSERT INTO WORKERS VALUES (p_id, p_PESEL,p_name,p_surname, p_date_birth,p_salary);
 ELSE
    DBMS_OUTPUT.PUT_LINE('Row can not be inserted.');
END IF;
 COMMIT;
EXCEPTION
 when DUP_VAL_ON_INDEX then
 dbms_output.put_line('DUP_VAL_ON_INDEX exception.');
  ROLLBACK;
END;

答案 1 :(得分:1)

我尝试了你的代码并没有任何问题,它按预期工作(执行两次时会落到dup_val_on_index异常)

我唯一能想到的可能是错误的是你没有定义主键或唯一键。 所以你的表定义应该是例如像这样

create table workers 
 (  id number,
    PESEL number,
    name varchar2(20),
    surname varchar2(20),
    date_birth date,
    salary number,
  CONSTRAINT worker_pk PRIMARY KEY (id)
)

或者您可以将主键或唯一键添加到现有列

alter table workers
  add constraint PK_workers primary key (ID);