Mysql触发器:在插入触发器之前实际设置了检查值

时间:2015-12-25 07:04:35

标签: mysql triggers beforeupdate

假设我有一张桌子。

CREATE TABLE IF NOT EXISTS Test (
  Id int(11) NOT NULL AUTO_INCREMENT,
  Foo tinyint(1) unsigned NOT NULL DEFAULT 0,
  Bar varchar(255) NOT NULL,
  PRIMARY KEY (Id)
);

在插入触发器之前:

DROP TRIGGER IF EXISTS `test_update`;
DELIMITER //
CREATE TRIGGER `test_update` BEFORE UPDATE ON `Test`
FOR EACH ROW BEGIN
  IF NEW.Foo IS NULL THEN
    -- do something
  END IF;
END
//
DELIMITER ;

通过触发器我检查Foo列是否实际传递到更新语句中。否则我会做点什么。

我的查询:

UPDATE Test
SET Bar = '23'
WHERE Id = 1;

如何正确检测Foo未设置?

1 个答案:

答案 0 :(得分:0)

您已创建表格:

[tinyint][1]: 1 byte, -128 to +127 / 0 to 255 (unsigned)

因此,由于mysql> INSERT INTO `Test` (`Id`, `Foo`, `Bar`) VALUES (1, 'ttt', 'La-la-la'); ERROR 1366 (HY000): Incorrect integer value: 'ttt' for column 'Foo' at row 1

,你永远不会在Foo'中获得NULL

快速测试:

{
  "firstName": "First Name 1",
  "headline": "Headline 1",
  "id": "MMk56SU",
  "industry": "Education",
  "lastName": "Last Name 1",
  "pictureUrl": "https://media.licdn.com/mpr/mprx/0_0FVMABigi5VY-wfOsimN0hTy6qn0-om7KFGcqGuy8qWY-Vj7JAG4shGykPWCAejmJAhBJ5Dp7_VOlmK7KN05J_8ro_VxlaMCzN0s-Cvj3Cf1U4COMLWqt9U2E9h74aaPycUvvK",
  "positions": {
    "_total": 1,
    "values": [{
      "company": {"name": "My Lovely College"},
      "id": 5960817,
      "isCurrent": true,
      "title": "Student"
    }]
  }
}