简体   繁体   中英

Syntax ERROR inside MySQL TRIGGER -> Insert Into Statement

I have a trigger that inserts new row into another table however there is an error somewhere as it tells me my values are NULL and they are not or at least they are not suppose to be.

Code of a TRIGGER

Delimiter //

CREATE TRIGGER new_active_user AFTER UPDATE ON `pre_reg`
FOR EACH ROW
BEGIN
    DECLARE currentUser INT;
    DECLARE banned INT;
    DECLARE user_type INT;
    DECLARE username VARCHAR (25);
    DECLARE password VARCHAR (60);
    DECLARE usersince datetime;
    DECLARE email varchar(40);
    SET @currentUser := (select `id` FROM `pre_reg` WHERE `active` = 1);
    SET @banned = 0;
    SET @user_type = 3;
    SET @username := (select `username` FROM `pre_reg` WHERE `id` = currentUser);
    SET @password := (select `password` FROM `pre_reg` WHERE `id` = currentUser);
    SET @usersince := (select `date` FROM `pre_reg` WHERE `id` = currentUser);
    SET @email := (select `email` FROM `pre_reg` WHERE `id` = currentUser);
    INSERT INTO `users` (`id`, `username`, `password`) VALUES (@currentUser, @username, @password);
END//
Delimiter ;

I even tried hard coding in the value of a currentUser in SET username, password, email SET statements. However It doesn't work I get following error:

Error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'username' cannot be null

I even tried to enter only ID (@currentUser) to make sure its set and the rest was hard coded (Works fine! So I assume that error is in the SET statements but can't figure out what it tells me always that value is NULL

This is how I have created the tables

CREATE TABLE `pre_reg` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `username` varchar(25) NOT NULL,
 `password` varchar(60) NOT NULL,
 `email` varchar(40) NOT NULL,
 `authentication` varchar(32) NOT NULL,
 `active` smallint(1) NOT NULL DEFAULT '0',
 `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`),
 UNIQUE KEY `username` (`username`,`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
GO
CREATE TABLE `users` (
`id` INT PRIMARY KEY,
`username` VARCHAR (25) NOT NULL,
`password` VARCHAR (60) NOT NULL,
`banned` SMALLINT NOT NULL DEFAULT 0,
`user_since` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
)ENGINE=InnoDB DEFAULT CHARSET=latin1
GO

This is probably what you want:

Delimiter //

CREATE TRIGGER new_active_user AFTER UPDATE ON `pre_reg`
FOR EACH ROW
BEGIN
    INSERT INTO `users` (`id`, `username`, `password`)
        VALUES (new.id, new.username, new.password);
END//
Delimiter ;

It inserts into the users table whatever what just updated in pre_reg .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM