仅当新值不为空或为null时才更新文本字段

时间:2014-06-29 13:50:40

标签: mysql sql

在我的表supportContacts中,我有一个名为comments的字段。我试图运行一个SQL查询,当字段不为空或为null时更新/附加新注释。此注释主要来自表单内的文本框区域,当用户提交为空时,查询不应更新数据库中的字段。下面的查询给了我一个错误。 SQLFIDDLE

UPDATE supportContacts SET IF(comments = CONCAT(comments, "Append this comment") IS NOT NULL or comments = '', 'empty', comments) WHERE id=1;

1 个答案:

答案 0 :(得分:1)

将条件放在where子句中:

UPDATE supportContacts
    SET Comments = CONCAT(comments, 'Append this comment')
    WHERE id = 1 and Comments is not null and Comments <> '';

编辑:

您可以测试附加值是NULL还是空:

UPDATE supportContacts
    SET Comments = CONCAT(comments, @AppendComments)
    WHERE id = 1 and Comments is not null and Comments <> '' and
          @AppendComments is not null and AppendComments <> '';

但我认为这就是你想要的:

UPDATE supportContacts
    SET Comments = CONCAT(coalesce(comments, ''), @AppendComments)
    WHERE id = 1 and @AppendComments is not null ;

如果新评论为空,则无效。即使现有注释为空,它也会附加新注释。