自动填充存储过程中的列值,通过触发器调用

时间:2011-04-08 07:45:39

标签: mysql stored-procedures triggers

目前,我有很多触发器可以做同样的事情。这是为需要此功能的每个表复制粘贴的。

delimiter $$

create trigger user_before_insert before insert on user for each row
begin
    set NEW.create_time = CURRENT_TIMESTAMP;
    set NEW.create_user_id = @user_id;
    set NEW.modify_time = CURRENT_TIMESTAMP;
    set NEW.modify_user_id = @user_id;
end$$

create trigger user_before_update before update on user for each row
begin
    set NEW.modify_time = CURRENT_TIMESTAMP;
    set NEW.modify_user_id = @user_id;
end$$

是否可以将修改OLD和/或NEW的行包装到通过触发器调用的存储过程中?像这样:

delimiter $$

create procedure autofill_on_insert(inout NEW data_type) -- what would be the data_type?
begin
    set NEW.create_time = CURRENT_TIMESTAMP;
    set NEW.create_user_id = @user_id;
    set NEW.modify_time = CURRENT_TIMESTAMP;
    set NEW.modify_user_id = @user_id;
end$$

create procedure autofill_on_update(inout NEW data_type) -- what would be the data_type?
begin
    set NEW.modify_time = CURRENT_TIMESTAMP;
    set NEW.modify_user_id = @user_id;
end$$

delimiter ;

create trigger user_before_insert before insert on user
    for each row call autofill_on_insert(NEW);
create trigger user_before_update before update on user
    for each row call autofill_on_update(NEW);

其他问题:如果可以,是否有办法检查NEW是否包含特定列?有些表没有modify_timemodify_user_id

1 个答案:

答案 0 :(得分:0)

我可以说NEW不能传递给过程,因为NEW是表示行的别名。过程的参数必须是标量值,如INT,VARCHAR等。

关于'SET NEW.create_time = CURRENT_TIMESTAMP;';如果字段create_time是TIMESTAMP,则可以将CURRENT_TIMESTAMP设置为默认值。