本文介绍了检测OLD值是否不等于NEW值并且OLD值为NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当OLD值不等于NEW值时,我想在audit_field中插入一行.为此,我在每个插入之前添加了IF NEW.notes <> OLD.notes THEN.但是,我发现(我认为)如果OLD值为NULL,则不会执行插入操作.我还没有测试过相反的说法是否正确,如果OLD值是某些值而NEW值是NULL,则不会插入,但是我希望不会.

I would like insert a row into audit_field when the OLD value is not equal to the NEW value. To do so, I added IF NEW.notes <> OLD.notes THEN before each of the inserts. I found (I think), however, that if the OLD value is NULL, then the insert isn't performed. I haven't tested whether the opposite is true, and it will not insert if the OLD value is something and the NEW value is NULL, but I expect it will not.

如何检测OLD值是否不等于NEW值且OLD值是否为NULL(或者类似的,如果NEW值为NULL)?

How do I detect if the OLD value is not equal to NEW value and OLD value was NULL (or similarly, if the NEW value is NULL)?

CREATE TRIGGER tg_students_upd AFTER UPDATE ON students
FOR EACH ROW 
BEGIN
    IF NEW.name <> OLD.name OR NEW.ssn <> OLD.ssn OR NEW.notes <> OLD.notes THEN
        INSERT INTO audits(tableName,pk,task,dateChanged,users_id,dbUser,requesting_ip) VALUES ('students', @AID, 'u', NOW(), @users_id, USER(), @requesting_ip );
        SET @AID=LAST_INSERT_ID();
        IF NEW.name <> OLD.name THEN
            INSERT INTO audit_field(audits_id,columnName,oldValue,newValue) VALUES (@AID,'name',OLD.name,NEW.name);
        END IF;
        IF NEW.ssn <> OLD.ssn THEN
            INSERT INTO audit_field(audits_id,columnName,oldValue,newValue) VALUES (@AID,'ssn',OLD.ssn,NEW.ssn);
        END IF;
        IF NEW.notes <> OLD.notes THEN
            INSERT INTO audit_field(audits_id,columnName,oldValue,newValue) VALUES (@AID,'notes',OLD.notes,NEW.notes);
        END IF;
    END IF;
END$$

推荐答案

使用<=>

SELECT NOT 1 <=> 1,NOT NULL <=> NULL, NOT 1 <=> NULL, NOT 1 <=> 2, 1 <> 1, NULL <> NULL, 1 <> NULL, 1 <>2;

+-------------+-------------------+----------------+-------------+--------+--------------+-----------+-------+
| NOT 1 <=> 1 | NOT NULL <=> NULL | NOT 1 <=> NULL | NOT 1 <=> 2 | 1 <> 1 | NULL <> NULL | 1 <> NULL | 1 <>2 |
+-------------+-------------------+----------------+-------------+--------+--------------+-----------+-------+
|           0 |                 0 |              1 |           1 |      0 | NULL         | NULL      |     1 |
+-------------+-------------------+----------------+-------------+--------+--------------+-----------+-------+

PS.抱歉,发布问题之前应该已经阅读了手册,但希望对您有所帮助.

PS. Sorry, should have read the manual before posting a question, but hopefully it will help someone else.

这篇关于检测OLD值是否不等于NEW值并且OLD值为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 03:53