3

我有下表test的字段

id (PK), 
Project Code (CFK), 
item code (CFK) 
date_code

行可能看起来像:

id, project code, item code, date code
1,  project1,     item1,     1220 
2,  project1,     item2,     1224
3,  project1,     item1,     null
3,  project1,     item4,     null
4,  project1,     item1,     null

要更新日期代码,我可以用一个简单的更新表来做到这一点

update table test
set date_code='1220' 
where project_code='project1' and item_code='item1'

但这可以通过插入和更新触发器来完成吗?

我希望触发器在更新表语法中找到相同/匹配的复合外键字段(项目代码和项目代码),并在日期代码字段的其他行中复制相同的值?

在给 date_code 字段赋值之前,所有行都将存在,因此它是最后完成的。

4

1 回答 1

4

你在寻找这样的东西吗?

CREATE TRIGGER tg_projects_insert
BEFORE INSERT ON projects
FOR EACH ROW
  SET NEW.date_code = IF(NULLIF(TRIM(NEW.date_code), '') IS NULL,
  (
    SELECT date_code 
      FROM projects
     WHERE project_code = NEW.project_code 
       AND item_code = NEW.item_code
     LIMIT 1
  ), NEW.date_code);

CREATE TRIGGER tg_projects_update
BEFORE UPDATE ON projects
FOR EACH ROW
  SET NEW.date_code = IF(NULLIF(TRIM(NEW.date_code), '') IS NULL,
  (
    SELECT date_code 
      FROM projects
     WHERE project_code = NEW.project_code 
       AND item_code = NEW.item_code
     LIMIT 1
  ), NEW.date_code);

现在我们可以在项目表中插入和更新行

-- insert a new row and let the trigger to set date_code automatically
INSERT INTO projects VALUES (5, 'project1', 'item1', NULL);

-- update all rows that currently have NULL in date_code 
-- and let the trigger to set date_code automatically
UPDATE projects SET date_code = NULL WHERE date_code IS NULL;

-- insert a new row and explicitly set a value to date_code
INSERT INTO projects VALUES (6, 'project2', 'item1', '1115');

这是SQLFiddle演示

于 2013-07-22T21:34:49.510 回答