1

这是数据库车辆表的触发器

DROP TRIGGER IF EXISTS InsertVehTrig;

DELIMITER $$

CREATE TRIGGER InsertVehTrig AFTER INSERT
ON Vehicle FOR EACH ROW
   SWL_return:
BEGIN
   DECLARE Cph CHAR(50);
   DECLARE DevID CHAR(12);
   DECLARE VehID BIGINT;
   DECLARE TmpID BIGINT;
   DECLARE DevCount INT;

   SET Cph = rtrim(ltrim(NEW.cph));
   SET VehID = NEW.ID;
   SET DevID = NEW.DevID;

   if(VehID is null) then 
    select count(id) into @DevCount from vehicle where (cph=@Cph) or (DevID=@DevID);
-- 条件:当前的车牌号 或 设备ID
    end if;

   if (DevCount > 1) then  -- 如果记录数,超过1,则认为有重复   
      -- Rollback not supported in trigger
        SET @SWV_Null_Var = 0;
        Leave SWL_return;
   else 
      if (DevCount = 1) then
         select ID INTO @TmpID from Vehicle where (Vehicle.cph = @Cph) or (Vehicle.DevID = @DevID);
         if (TmpID != VehID) then -- --如果增加的车牌号码与数据库中的在相同的,则不允许增加
            -- Rollback not supported in trigger
                Leave SWL_return;
                SET @SWV_Null_Var = 0;
         end if;
      end if;
   end if;

   update vehicle set cph = @Cph where ID = @VehID;
END;

现在我试图在车辆表中插入新的数据行,但是这个错误

ERROR 1442: Can't update table 'vehicle' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

SQL Statement:

INSERT INTO `gis_server`.`vehicle` (`TrackerNum`, `cph`, `DevID`, `DevType`) VALUES ('1', 'NR09B00555', 'NR09B00555', '2')

这些数据库是由 3 方公司设计的,
我如何将数据插入车辆表?

4

1 回答 1

0

您可以通过对方法进行两项更改来实现此目的:

  • 首先,使用BEFORE触发器而不是AFTER
  • 其次,不是更新同一个表,而是更新表,在表命中目标表NEW之前将列值设置为新值。NEWINSERT

例如,将您的UPDATE行替换为以下内容:

UPDATE NEW SET cph = Cph;

MySQL 不允许您编辑在该触发器中创建触发器的表中的数据,但您可以编辑该NEW表以修改进入该表的值。

于 2013-08-15T20:13:43.920 回答