Mysql trigger makes queries take unlimited time

Webdev :

I have a students table which includes following fields

Student_Id int primary key

student_name varchar(50)

seat_number varchar(50)

level_id int foreign key

CREATE TABLE `students` (
`Student_Id` int(11) NOT NULL AUTO_INCREMENT,
`student_name` varchar(100) DEFAULT NULL,
`level_id` int(11) DEFAULT NULL,
`seat_number` varchar(50) DEFAULT NULL,
 KEY `Relationship17` (`level_id`),
 CONSTRAINT `Relationship17` FOREIGN KEY (`level_id`) REFERENCES `levels` (`Level_Id`) ON DELETE CASCADE ON UPDATE CASCADE)

My goal

To set unique values to seat_number field using query

FLOOR(rand() * 90000 + 10000)

And then to concat the result to a character based on level_id value.

So I create following trigger:

DELIMITER $$
CREATE TRIGGER seat_nu_trigger BEFORE INSERT ON students FOR EACH ROW
BEGIN
DECLARE x CHARACTER;
DECLARE cur cursor for select FLOOR(rand() * 90000 + 10000) from students;
open cur;
if NEW.level_id=1 THEN
set x = 'A';
ELSEIF
NEW.level_id=2 THEN
set x = 'B'; 
END IF;
getSeatNumber: LOOP
SET NEW.seat_number = concat(x,FLOOR(rand() * 90000 + 10000) );
END LOOP getSeatNumber;
CLOSE cur;
END;

The problem

When I insert any data to my table it doesn't inserted and the query takes unlimited time.

I cannot drop the trigger.

Akina :
CREATE TRIGGER seat_nu_trigger 
BEFORE INSERT 
ON students 
FOR EACH ROW
SET NEW.seat_number = CONCAT(CASE NEW.level_id WHEN 1 THEN 'A'
                                               WHEN 2 THEN 'B'
                                               END, FLOOR(rand() * 90000 + 10000) );

PS-1. If level_id is set to some other than A or B then seat_number will be set to NULL.

PS-2. seat_number length will be variable. Think about additional LPAD().

PS-3. seat_number uniqueness is not guaranteed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216807&siteId=1