Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
929 views
in Technique[技术] by (71.8m points)

sql - How to replace non-numeric characters in MySQL?

I want to replace all non-numerical characters in a VARCHAR field in MySQL, because is a phone table and while importing them I found several "Fax:xxx" or "-" characters that shouldn't be there.

I'd prefer a solution that not involves multiple REPLACE() calls,

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a mysql function:

delimiter //

create function IF NOT EXISTS LeaveNumber(str varchar(50)) returns varchar(50)
no sql
begin
declare verification varchar(50);
declare result varchar(50) default '';
declare character varchar(2);
declare i integer default 1;

if char_length(str) > 0 then
    while(i <= char_length(str)) do
        set character = substring(str,i,1);
        set verification = find_in_set(character,'1,2,3,4,5,6,7,8,9,0');

        if verification > 0 then
            set result = concat(result,character);
        end if;

        set i = i + 1;

    end while;

return result;
else
return '';
end if;
end //


delimiter ;

select leaveNumber('fAX:-12abcDE234'); -- RESULT: 12234

Use it as a native mysql function in your update query.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...