触发工作正常,但插入错误

时间:2016-12-10 19:24:12

标签: mysql triggers insert

我在表格中有以下触发器:

DELIMITER //

CREATE TRIGGER trReportInsertLog

AFTER INSERT ON repport_table

FOR EACH ROW

BEGIN

DECLARE last_id int;
SELECT LAST_INSERT_ID() INTO last_id;

INSERT INTO systemlog_table (Id, Description)
VALUES ('', 'Created a new Report with Id = '+last_id); /* PROBLEM HERE */

END; //
DELIMITER ;

我遇到的问题是插入值时的问题。 第一个值为空,因为它是auto_increment列。 (工作正常)

另一个值是一个字符串,但只有' last_id'插入。

我认为这可能是引用错误的。我尝试了多种方法,但我无法让它发挥作用。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

mysql> DROP TABLE IF EXISTS `systemlog_table`;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP TABLE IF EXISTS `repport_table`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE `repport_table` (
    ->   `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    ->   `current_at` TIMESTAMP NOT NULL,
    ->   PRIMARY KEY (`id`)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE `systemlog_table` (
    ->   `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    ->   `description` VARCHAR(255) NOT NULL,
    ->   PRIMARY KEY (`id`)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER $$

mysql> DROP TRIGGER /*!50032 IF EXISTS */ `trReportInsertLog`$$
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CREATE TRIGGER `trReportInsertLog` AFTER INSERT ON `repport_table`
    -> FOR EACH ROW
    -> BEGIN
    ->     /*
   /*>     DECLARE last_id int;
   /*>     SELECT LAST_INSERT_ID() INTO last_id;
   /*> 
   /*>     INSERT INTO systemlog_table (Id, Description)
   /*>     VALUES ('', 'Created a new Report with Id = '+last_id); /* PROBLEM HERE *\/
   /*>     */
    -> 
    ->     INSERT INTO `systemlog_table` (`description`)
    ->     VALUES (CONCAT('Created a new Report with Id = ', NEW.`id`));
    -> END$$
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> INSERT INTO `repport_table` (`current_at`)
    -> VALUES (NOW());
Query OK, 1 row affected (0.00 sec)

mysql> SELECT `id`, `current_at`
    -> FROM `repport_table`;
+----+---------------------+
| id | current_at          |
+----+---------------------+
|  1 | 2000-01-01 00:00:01 |
+----+---------------------+
1 row in set (0.00 sec)

mysql> SELECT `id`, `description`
    -> FROM `systemlog_table`;
+----+----------------------------------+
| id | description                      |
+----+----------------------------------+
|  1 | Created a new Report with Id = 1 |
+----+----------------------------------+
1 row in set (0.00 sec)