Does the MySQL TRIM function not trim line breaks or carriage returns?

后端 未结 10 1762
旧时难觅i
旧时难觅i 2020-12-03 13:58

From my experiments, it does not appear to do so. If this is indeed true, what is the best method for removing line breaks? I\'m currently experimenting with the parameters

相关标签:
10条回答
  • 2020-12-03 14:01

    i could only get it to work by making the char;

    trim(both char(13) from fieldname)
    
    0 讨论(0)
  • 2020-12-03 14:04

    I faced the same issue with one of the fields. There is no perfect solution. In my case i was lucky that the length of the field was supposed to be 6. So i used a query like

    update events set eventuniqueid = substring(eventuniqueid, 1, 6) where length(eventuniqueid) = 7;
    

    You will just have to choose the best option based on your need. The replace '\n' and '\r\n' did not work for me and just ended up wasting my time.

    0 讨论(0)
  • 2020-12-03 14:05

    The standard MySQL trim function is not like trim functions in any other languages I know as it only removes exact string matches, rather than any characters in the string. This stored function is more like a normal trim you'd find in PHP, or strip in python etc.

    CREATE FUNCTION `multiTrim`(string varchar(1023),remove varchar(63)) RETURNS varchar(1023) CHARSET utf8
    BEGIN
      -- Remove trailing chars
      WHILE length(string)>0 and remove LIKE concat('%',substring(string,-1),'%') DO
        set string = substring(string,1,length(string)-1);
      END WHILE;
    
      -- Remove leading chars
      WHILE length(string)>0 and remove LIKE concat('%',left(string,1),'%') DO
        set string = substring(string,2);
      END WHILE;
    
      RETURN string;
    END;
    

    You should then be able to do:

    select multiTrim(string,"\r\n\t ");
    

    and it should remove all newlines, tabs and spaces.

    0 讨论(0)
  • 2020-12-03 14:06

    Yes, Trim() will work in MySQL. You have two choices.

    1) select it out:

    select trim(BOTH '\n' from [field_name]) as field
    

    If that doesn't work, try '\r', if that doesn't work, try '\n\r'.

    2) replace the bad data in your table with an update...

    update [table_name] set [field_name] = trim(BOTH '\n' from [field_name])
    

    I recommend a select first to determine which line break you have (\r or \n).

    0 讨论(0)
  • 2020-12-03 14:11

    Trim() in MySQL only removes spaces.

    I don't believe there is a built-in way to remove all kinds of trailing and leading whitespace in MySQL, unless you repeatedly use Trim().

    I suggest you use another language to clean up your current data and simply make sure your inputs are sanitized from now on.

    0 讨论(0)
  • 2020-12-03 14:16
    select trim(both '\n' from FIELDNAME) from TABLE;
    
    0 讨论(0)
提交回复
热议问题