To add characters to a result, you can use the INSERT
function. Do not confuse with the syntax INSERT INTO
, we are talking about the string function.
SELECT INSERT( INSERT( INSERT( cpf, 10, 0, '-' ), 7, 0, '.' ), 4, 0, '.' )
Explaining:
Syntax:
INSERT(str,pos,len,newstr)
│ │ │ └───── string a ser inserida
│ │ └────────── quantos caracteres serão deletados na posição
│ └────────────── posição onde a string será inserida
└────────────────── campo desejado ou string original
PHP Equivalent:
substr_replace(substr_replace(substr_replace( $cpf, '-', 9, 0 ), '.', 6, 0 ), '.', 3, 0 );
An alternative would be to use CONCAT
to pick up each "piece" of the CPF, and paste the pieces and divisors using SUBSTR
:
SELECT CONCAT(SUBSTR(cpf,1,3),'.',SUBSTR(cpf,4,3),'.',SUBSTR(cpf,7,3),'-',SUBSTR(cpf,10,2))
I think that SUBSTR
is nicer in this case (at least a lot shorter to write, in addition to referencing the field in one place only).
In any case, the second example may be useful for other uses. It's not as noble as a kintsugi , but CONCAT
has its moments of glory.
PHP Equivalent:
substr($cpf,0,3).'.'.substr($cpf,3,3).'.'.substr($cpf,6,3).'-'.substr($cpf,9,2);