MYSQL Trigger set datetime value using case statement

不想你离开。 提交于 2019-12-23 17:43:28

问题


I'm using mysqlimport to do mass table inserts (replacing duplicates primary keys). Several tables have date time columns with records containing values '0000-00-00'. What I would like is a trigger which detects these '0000-00-00' values and replaces with '1950-01-01', otherwise keep the datetime value in the record (i.e. when it's not '0000-00-00').

I have tried the following:

CREATE TRIGGER set_datetime BEFORE INSERT ON tbl
FOR EACH ROW
CASE
WHEN date_col='0000-00-00' THEN SET date_col='1950-01-01';
END CASE

Thank you.

EDIT

Update attempt:

CREATE TRIGGER set_datetime BEFORE INSERT ON tbl
FOR EACH ROW
IF (NEW.date_col='0000-00-00') THEN
SET NEW.date_col='1950-01-01';
END IF;

Still getting an error in the SET portion.

EDIT 2

WORKING:

DELIMITER $$
CREATE TRIGGER insert_check BEFORE INSERT ON ar
FOR EACH ROW
BEGIN
    IF NEW.delivery_date='0000-00-00' THEN
        SET NEW.delivery_date='1950-01-01';
    END IF;
END; $$
DELIMITER ;

回答1:


Use IF THEN :

IF (NEW.date_col = '0000-00-00') THEN
  SET NEW.date_col='1950-01-01';
END IF;



回答2:


CREATE TRIGGER set_datetime BEFORE INSERT ON tbl 
FOR EACH ROW 
IF YEAR(NEW.date_col)=0 THEN
    SET NEW.date_col='1950-01-01 00:00:00'; 
END IF; 

Give it a Try !!!




回答3:


If you want, or need, to use 'case' then this should work:

SET NEW.date_col=CASE WHEN NEW.date_col='0000-00-00' THEN ='1950-01-01'
WHEN NEW.date_col='something else' THEN 'whatever'
ELSE 'default'
END CASE;


来源:https://stackoverflow.com/questions/8419957/mysql-trigger-set-datetime-value-using-case-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!