无法从触发器内的SELECT查询中获取值

时间:2012-04-02 13:48:54

标签: mysql triggers

我正在编写一个触发器来更新另一个表上的POSTTER INSERT表中的行。以下是表格的脚本:

inv_cost

CREATE TABLE inv_cost (
  Username varchar(20) NOT NULL DEFAULT '',
  MachineType varchar(2) NOT NULL,
  Cost smallint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (Username,MachineType),
)

调查

CREATE TABLE investigation (
  Username varchar(20) NOT NULL,
  MachineType varchar(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DELIMITER ;;
CREATE TRIGGER TRG1 AFTER INSERT ON investigation FOR EACH ROW BEGIN
    DECLARE cost INT DEFAULT 0;
    SET cost = (SELECT Cost FROM inv_cost WHERE Username = NEW.Username AND MachineType = NEW.MachineType);
    UPDATE test SET Balance = Balance - cost WHERE Username = New.Username;
END;;
DELIMITER ;

调查员

CREATE TABLE test (
  ID int(10) unsigned NOT NULL AUTO_INCREMENT,
  Username varchar(20) NOT NULL DEFAULT '',
  Balance smallint(6) DEFAULT NULL,
  PRIMARY KEY (ID)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
DELIMITER ;;
CREATE TRIGGER TRG2 AFTER UPDATE ON test FOR EACH ROW BEGIN
    IF NEW.Balance > OLD.Balance THEN
        INSERT INTO payments SET Username = NEW.Username, PaymentOn = NOW(), Amount = NEW.Balance - OLD.Balance;
    END IF;
END;;
DELIMITER ;

触发器 TRG1 的问题在于它不会从SELECT语句计算变量 cost 的值,并始终取值0或设置为声明默认。下一行的UPDATE查询效果很好( cost 从其声明中获取值,或者如果赋值为SET cost = 100;)则为其值。 SELECT运行单独提供成本所需的值。

此代码有什么问题?

提前致谢。

1 个答案:

答案 0 :(得分:1)

你必须使用语法 SELECT字段FROM表WHERE条件INTO变量

DROP TRIGGER TRG1 IF EXISTS;
DELIMITER $$
 CREATE TRIGGER TRG1
 AFTER INSERT ON investigation
 FOR EACH ROW BEGIN
      DECLARE cst smallint;
      SELECT Cost FROM inv_cost WHERE Username = NEW.Username AND MachineType = NEW.MachineType INTO cst;
      UPDATE test SET Balance = Balance - cst WHERE Username = New.Username;
 END$$
 DELIMITER ;