MySQL select fields containing leading or trailing whitespace

后端 未结 4 806
轻奢々
轻奢々 2021-01-03 18:42

I can use the MySQL TRIM() method to cleanup fields containing leading or trailing whitespace with an UPDATE like so:

UPDATE Foo SE         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-03 19:15

    Another solution could be using SUBSTRING() and IN to compare the last and first characters of the string with a list of whitespace charaters...

    (SUBSTRING(@s,  1, 1) IN (' ', '\t', '\n', '\r') OR SUBSTRING(@s, -1, 1) IN (' ', '\t', '\n', '\r'))
    

    ...where @s is any input string. Add additional whitespace characters to the comparison list as needed in your case.

    Here's a simple test to demonstrate how that expression behaves with various string inputs:

    SET @s_normal = 'x';
    SET @s_ws_leading = '\tx';
    SET @s_ws_trailing = 'x ';
    SET @s_ws_both = '\rx ';
    
    SELECT
        NOT(SUBSTRING(@s_normal,      1, 1) IN (' ', '\t', '\n', '\r') OR SUBSTRING(@s_normal,     -1, 1) IN (' ', '\t', '\n', '\r')) test_normal      #=> 1 (PASS)
      ,    (SUBSTRING(@s_ws_leading,  1, 1) IN (' ', '\t', '\n', '\r') OR SUBSTRING(@s_ws_leading, -1, 1) IN (' ', '\t', '\n', '\r')) test_ws_leading  #=> 1 (PASS)
      ,    (SUBSTRING(@s_ws_trailing, 1, 1) IN (' ', '\t', '\n', '\r') OR SUBSTRING(@s_ws_trailing,-1, 1) IN (' ', '\t', '\n', '\r')) test_ws_trailing #=> 1 (PASS)
      ,    (SUBSTRING(@s_ws_both,     1, 1) IN (' ', '\t', '\n', '\r') OR SUBSTRING(@s_ws_both,    -1, 1) IN (' ', '\t', '\n', '\r')) test_ws_both     #=> 1 (PASS)
    ;
    

    If this is something you'll be doing a lot you could also create a function for it:

    DROP FUNCTION IF EXISTS has_leading_or_trailing_whitespace;
    
    CREATE FUNCTION has_leading_or_trailing_whitespace(s VARCHAR(2000))
      RETURNS BOOLEAN
      DETERMINISTIC
    RETURN (SUBSTRING(s, 1, 1) IN (' ', '\t', '\n', '\r') OR SUBSTRING(s, -1, 1) IN (' ', '\t', '\n', '\r'))
    ;
    
    # test
    SELECT
        NOT(has_leading_or_trailing_whitespace(@s_normal     )) #=> 1 (PASS)
      ,     has_leading_or_trailing_whitespace(@s_ws_leading )  #=> 1 (PASS)
      ,     has_leading_or_trailing_whitespace(@s_ws_trailing)  #=> 1 (PASS)
      ,     has_leading_or_trailing_whitespace(@s_ws_both    )  #=> 1 (PASS)
    ;
    

提交回复
热议问题