如何验证记录是否已存在?

时间:2019-09-20 21:34:57

标签: mysql stored-procedures do-while exists

我在sql中有此存储过程,我将csv格式的员工导入到时态表中,然后在不存在员工的情况下进行插入,或者在员工已经存在的情况下进行更新

我尝试过一个if,然后我考虑过使用一会儿,但似乎找不到正确的解决方案

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_import_employees`()
BEGIN
DECLARE n INT;
DECLARE total INT;
SET n = 0;
SELECT COUNT(*) FROM temp into total;
SET FOREIGN_KEY_CHECKS=0;
SET AUTOCOMMIT=0;
START TRANSACTION;
WHILE n<=total DO
IF EXISTS (SELECT t.idemployee FROM temp t WHERE EXISTS (SELECT e.idemployee FROM employee e WHERE e.idemployee = t.idemployee)) THEN
    BEGIN
        SELECT 'Update employee';
    END;
ELSE
    BEGIN
        SELECT 'New employee';
        INSERT INTO person(fname,lname,email) 
        SELECT t.fname, t.lname, t.email
        FROM temp t;
        INSERT INTO department(description,jobtitle) 
        SELECT t.description,t.jobtitle
        FROM temp t;
        COMMIT;
        INSERT INTO employee(idperson,idemployee,status,hiredate,idsupervisor,iddepartment,country,site,clockid) 
        SELECT p.idperson,t.idemployee,t.statu,t.hiredate,t.idsupervisor,d.iddepartment,t.country,t.site,t.clockid
        FROM temp t
        INNER JOIN person p ON t.idtemp = p.idperson
        INNER JOIN department d ON p.idperson = d.iddepartment;
        COMMIT;
    END;
END IF;
END WHILE;  
END

现在我被这段代码困在无限循环中

0 个答案:

没有答案