我有一些具有相同字段值的表,不能重复。我决定在制作INSERT时创造价值。触发器获取最大值并添加1.但在SELECT MAX(account_number) AS last_account_number INTO last_account_number FROM companies;
last_account_number之后始终为null,但值为,并且外部请求触发器本身运行顺利。
CREATE TRIGGER generate_account_number_for_companies
before insert
ON companies FOR EACH ROW
BEGIN
DECLARE account_number INT;
DECLARE last_account_number INT;
SELECT MAX(account_number) AS last_account_number INTO last_account_number FROM companies;
IF last_account_number is null THEN
SET New.account_number = 10000000;
ELSE
SET New.account_number = last_account_number + 1;
END IF;
END
答案 0 :(得分:1)
首先,您的AS last_account_number
声明中不需要SELECT ... INTO
部分。其次,您当前的companies
表中是否有数据,或者它是否为空?如果它不为空,请尝试修改语句以排除NULL
值:
SELECT MAX(account_number) INTO last_account_number FROM companies WHERE account_number IS NOT NULL;
如果coalesce
返回,您还可以在其中添加0
以将其设置为NULL
。
SELECT COALESCE(MAX(account_number), 0) INTO last_account_number FROM companies WHERE account_number IS NOT NULL;
您还要声明一个与您尝试选择的列名称相同的变量,从触发器中删除该行:DECLARE account_number INT;
。