我有两张桌子:
CREATE TABLE EMPLOYEE (
EMPLOYEE_ID bigint NOT NULL AUTO_INCREMENT,
EMPLOYEE_NO VARCHAR(30),
EMPLOYEE_TYPE VARCHAR(20),
PRIMARY KEY(EMPLOYEE_ID)
);
CREATE TABLE EMP_DETAIL(
EMPLOYEE_ID BIGINT NOT NULL ,
INS_ID VARCHAR(20) ,
SALARY int,
PRIMARY KEY(EMPLOYEE_ID ,INS_ID),
FOREIGN KEY(EMPLOYEE_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID)
);
我想在emp表和emp_detail表中插入一个值。如果员工已存在,则只在emp_details表中插入记录。
这是存储过程:
CREATE PROCEDURE INSERTEMP(
IN EMPLOYEE_NO VARCHAR(30),
IN EMPLOYEE_TYPE VARCHAR(20),
IN INS_ID VARCHAR(20),
IN SALARY INT
)
BEGIN
DECLARE EMPLOYEE_ID BIGINT;
SET @EMPLOYEE_ID= (SELECT IFNULL((SELECT EMPLOYEE_ID FROM EMPLOYEE WHERE EMPLOYEE_NO=EMPLOYEE_NO AND EMPLOYEE_TYPE=EMPLOYEE_TYPE) ,'0'));
IF @EMPLOYEE_ID=0 THEN
INSERT INTO EMPLOYEE (EMPLOYEE_NO ,EMPLOYEE_TYPE ) VALUES (EMPLOYEE_NO,EMPLOYEE_TYPE);
SET @EMPLOYEE_ID=(SELECT LAST_INSERT_ID());
END IF;
INSERT INTO EMP_DETAIL(EMPLOYEE_ID,INS_ID,SALARY) VALUES (@EMPLOYEE_ID,INS_ID,SALARY);
END
如果我致电程序:
CALL INSERTEMP(100, 'PERM','AAA',100);
首先在emp表中执行它创建的id为1,如果在第二次执行它也插入新的id并且第三次失败。
有人可以帮忙吗?