“select”和“insert into”由mysql事件执行多行操作

xpszyzbs  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(423)

我需要写一封信 MySql Event 在某些条件下从表中选择一些值并将这些值放入第二个表中。通过select语句。我得到多行,所以我需要在第二个表中批量存储数据。我怎样才能做到这一点?我编写了一个事件来选择一行。但我需要做的是选择多个行并作为一个批存储。
我写的事件如下。

DELIMITER $$
  CREATE EVENT salary_add
  ON SCHEDULE EVERY 24 HOUR
  DO
  BEGIN
  DECLARE month_end DATETIME;
  DECLARE today DATETIME;
  DECLARE reg_id VARCHAR(6);
  DECLARE sal INT(8);
  SET month_end = LAST_DAY(DATE(NOW()));
  SET today = DATE(NOW());

   IF month_end=today THEN
   SELECT register_id,salary INTO reg_id,sal FROM employees 
   WHERE status ='1' LIMIT 1;
   INSERT INTO tbl_salary (register_id,amount,salary_date,status) VALUES (reg_id,sal,today,'0');
   END IF;
   END $$
DELIMITER ;
jv4diomz

jv4diomz1#

可以将选定的行一次插入到目标表中。例如:

DELIMITER $$
  CREATE EVENT salary_add
  ON SCHEDULE EVERY 24 HOUR
  DO
  BEGIN
    DECLARE month_end DATETIME;
    SET month_end = LAST_DAY(CURDATE());

    IF month_end=CURDATE() THEN   
      INSERT INTO tbl_salary (register_id, amount, salary_date, status)
      SELECT register_id,
             salary,
             CURDATE(),
             '0'
      FROM employees
      WHERE status ='1'
    END IF;
  END $$
DELIMITER ;

相关问题