MySQL 使用 CONCAT_WS 更新触发器后:为什么它会在我不想要的地方插入换行符?

MySQL after update trigger using CONCAT_WS: Why is it inserting a newline where I DON'T want it?

预期的结果是将对一个字段的编辑注释存储在另一个字段中。 我希望将新注释附加到存储字段,并且由于这不是执行此操作的函数,所以我正在尝试找到一种方法来解决这个问题,而无需添加更多层代码(如函数和存储过程)。

/* Before Update Trigger */

DECLARE v_description VARCHAR(255);
DECLARE v_permnotes MEDIUMTEXT;
DECLARE v_oldnote VARCHAR(500);
DECLARE v_now VARCHAR(25);

SET v_now = TRIM(DATE_FORMAT(NOW(), '%Y-%m-%d %k:%i:%s'));

SET v_oldnote = OLD.notes;

IF (NEW.permanent_notes IS NULL) THEN
  SET v_permnotes = '';
ELSE
  SET v_permnotes = OLD.permanent_notes;
END IF;

SET NEW.permanent_notes = CONCAT_WS(CHAR(10), v_permnotes, v_now,": ", v_description);

我的目标是让永久字段中的结果看起来像这样

<datetime value>: Some annotation from the notes field.
<a different datetime>: A new annotation
etc....

我从当前触发器中得到的:

2018-12-30 17:15:50
: 
Test 17: Start from scratch. 
2018-12-30 17:35:51
: 
Test 18: Used DATE_FORMAT to sxet the time 
2018-12-30 17:45:52
: 
Test 19. Still doing a carriage return after date and after ':'

我不明白为什么在日期之后有一个换行符,然后在“:”之后又有一个换行符。

如果我省略 CHAR(10),我得到:

Test 17: Start from scratch. 
2018-12-30 17:35:51
: 
Test 18: Used DATE_FORMAT to sxet the time 
2018-12-30 17:45:52
: 
Test 19. Still doing a carriage return after date and after ':'Test 20. Still doing a carriage return after date and after ':'

一些 fresh/more 有经验的人会对调试这个问题很有帮助。

谢谢。

我认为你应该在这里使用纯 CONCAT

DECLARE separator VARCHAR(1);

IF (NEW.permanent_notes IS NULL) THEN
    SET separator = '';
ELSE
   SET separator = CHAR(10)
END IF;

-- the rest of your code as is

SET
    NEW.permanent_notes = CONCAT(v_permnotes, separator, v_now, ": ", v_description);

这里的逻辑是我们有条件地打印换行符 (CHAR(10)) before 每个新的日志行,只要该行不是第一行。这里其实不需要CONCAT_WS,主要是为了在多个term之间加一个分隔符。您只需要在每个日志记录语句之间有一个换行符。