BEGIN DECLARE count INT; SELECT COUNT(*) into count from reserve where r_time=NEW.r_time AND d_id=NEW.d_id; IF EXISTS (SELECT work_start FROM work WHERE work_start = CONCAT(DATE_FORMAT(NEW.r_time, '%W%H:%i'))) THEN INSERT INTO reserve (r_id, p_id, d_id, r_time, r_status, r_out_num) VALUES (New.r_id, New.p_id, New.d_id, New.r_time, '已预约', null); ELSE SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Data does not meet the requirements'; END IF; SELECT renshu into @num from work where d_id=NEW.d_id AND work_start = CONCAT(DATE_FORMAT(NEW.r_time, '%W%H:%i')) LIMIT 1; IF count <= @num THEN UPDATE reserve SET r_out_num = @num - count, d_id = NEW.d_id WHERE r_time = NEW.r_time AND d_id = NEW.d_id; ELSE SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Appointment limit exceeded'; END IF; END不想要updat那步,能不能把两次判断合并,一次性插入
时间: 2024-03-28 15:37:54 浏览: 54
可以将两次判断合并,可以使用IF语句的嵌套来实现。以下是修改后的代码:
BEGIN
DECLARE count INT;
SELECT COUNT(*) into count from reserve where r_time=NEW.r_time AND d_id=NEW.d_id;
SELECT renshu into @num from work where d_id=NEW.d_id AND work_start = CONCAT(DATE_FORMAT(NEW.r_time, '%W%H:%i')) LIMIT 1;
IF EXISTS (SELECT work_start FROM work WHERE work_start = CONCAT(DATE_FORMAT(NEW.r_time, '%W%H:%i')))
THEN
IF count <= @num
THEN
INSERT INTO reserve (r_id, p_id, d_id, r_time, r_status, r_out_num) VALUES (New.r_id, New.p_id, New.d_id, New.r_time, '已预约', @num - count);
ELSE
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Appointment limit exceeded';
END IF;
ELSE
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Data does not meet the requirements';
END IF;
END
在这个修改后的代码中,首先声明了count变量和@num变量,然后查询reserve表中符合条件的行数和work表中的人数限制。然后,使用IF语句的嵌套,将两次判断合并,并根据条件执行相应的操作。如果work表中存在符合条件的数据,则判断预约人数是否已达到人数限制,如果没有达到,则插入预约数据,并更新r_out_num字段;如果已达到,则抛出异常。如果work表中不存在符合条件的数据,则同样抛出异常。
阅读全文