Mysql format a string like XXXXXXXXXXXX to XX-XX-XXXXXXX-X

后端 未结 3 1854
栀梦
栀梦 2021-01-26 09:50

I need a string that looks like XXXXXXXXXXXX to look like this XX-XX-XXXXXXX-X. I don\'t know of a function or pattern tool in MySQL that can do this. Do you?

相关标签:
3条回答
  • 2021-01-26 10:09

    Take a look at this, I think that's exactly what you are look for.

    MySQL output masking (i.e. phone number, SSN, etc. display formatting)

    0 讨论(0)
  • 2021-01-26 10:13

    One way to do that, in MySQL is to use an expression with the SUBSTRING and CONCAT functions, Like this:

    CONCAT(
      SUBSTR(str,1,2), 
      '-',
      SUBSTR(str,3,2),
      '-',
      SUBSTR(str,5,7),
      '-',
      SUBSTR(str,12,1)
     ) AS formatted_str
    
    0 讨论(0)
  • 2021-01-26 10:13

    if the length of the string is fix, you can just simple string manipulation

    SELECT pat,
           CONCAT_WS('-', SUBSTR(pat,1,2), 
                           SUBSTR(pat,3,2),
                           SUBSTR(pat,5,7),
                           RIGHT(pat,1))
    FROM   tableName
    
    • SQLFiddle Demo
    0 讨论(0)
提交回复
热议问题