我想删除一个删除语句,如果它带来的行数低于2000:
CREATE TRIGGER Trig1
AFTER DELETE ON Tab1
FOR EACH ROW
IF (SELECT COUNT(*) FROM Table1) < 2000
BEGIN
INSERT INTO Table1 (select * from old);
END;
END IF;
但它不起作用。有人可以告诉我我做错了什么,以及它应该如何看待?
答案 0 :(得分:1)
试,
INSERT INTO Table1
SELECT *
FROM old
指向记住
*
答案 1 :(得分:0)
您可以尝试以下代码:
DELIMITER $$
DROP TRIGGER IF EXISTS `Trig1`$$
CREATE TRIGGER `Trig1`
AFTER DELETE ON Table1
FOR EACH ROW
BEGIN
IF (SELECT COUNT(*) FROM Table1) < 2000 THEN
INSERT INTO Table2(field1, field2, field3) VALUES(old.field1, old.field2, old.field3);
END IF;
END$$
DELIMITER ;
我已经对它进行了测试,并且它可以在我的最终使用。
答案 2 :(得分:0)
如果操作会导致记录太少,那么通过创建引发错误的BEFORE DELETE
触发器(从而导致语句中止),您会更好:
DELIMITER ;;
CREATE TRIGGER foo BEFORE DELETE ON Table1 FOR EACH ROW
IF (SELECT COUNT(*) FROM Table1) <= 2000 THEN SIGNAL SQLSTATE '45000' SET
MESSAGE_TEXT = 'Cannot delete when table would result in too few records';
END IF;;
DELIMITER ;
请注意,SIGNAL
仅在MySQL 5.5中引入。如果使用早期版本,则必须强制MySQL通过执行错误操作来引发异常;我经常CALL
一个不存在的程序,例如CALL raise_error;
。