2016-07-20 9 views
0

文字列から郵便番号を抽出したい。 だから当然、私はこのような何かを考えた:instr()を使用したMysql部分文字列

substring(PERSON_ADDRESS, instr(PERSON_ADDRESS,'[0-9][0-9][0-9][0-9][0-9]'), 5)

ああ、これを行う方法のための任意のアイデア

(それは0を返す)instr(str, '[0-9])は、MySQLで有効なものではないようですか?

多くの感謝!

+1

私は 'INSTR'が正規表現をサポートしているとは思わない。あなたが抽出しようとしているサンプルを使用することができますか? –

+0

PERSON_ADDRESSの例を表示すると、抽出の方法がわかります – RiggsFolly

+0

私の最初の考えは、データベース設計に基本的な誤りがあったということですが、郵便番号が自分の列にないのです。 – RiggsFolly

答えて

1

あなたはユーザー定義関数を作成します - 限り、潜在的な郵便番号をスペースで囲まれたか、これは

drop function if exists tokens; 
delimiter // 
create  function tokens(instring varchar(255)) 
returns varchar(255) 
begin 
declare tempstring varchar(100); 
declare outstring varchar(100); 
declare checkit int; 
set tempstring = ltrim(rtrim(instring)); 
set checkit = 0; 
looper: while tempstring is not null and instr(tempstring,' ') > 0 do 
     set outstring = substr(tempstring,1,instr(tempstring, ' ') - 1); 
     set tempstring = ltrim(rtrim(replace(tempstring,outstring,''))); 
     if length(outstring) = 5 then 
      if substring(outstring,1,1) between char(48) and char(57) and 
       substring(outstring,2,1) between char(48) and char(57) and 
       substring(outstring,3,1) between char(48) and char(57) and 
       substring(outstring,4,1) between char(48) and char(57) and 
       substring(outstring,5,1) between char(48) and char(57) then 
       set checkit = 1; 
       leave looper; 
      end if; 
     end if; 
end while; 
if checkit = 0 then 
    set outstring = tempstring; 
      if length(outstring) = 5 then 
      if substring(outstring,1,1) between char(48) and char(57) and 
       substring(outstring,2,1) between char(48) and char(57) and 
       substring(outstring,3,1) between char(48) and char(57) and 
       substring(outstring,4,1) between char(48) and char(57) and 
       substring(outstring,5,1) between char(48) and char(57) then 
       set checkit = 1; 
      end if; 
     end if; 
end if; 

if checkit = 0 then set outstring = 'NotFound'; end if; 
return outstring; 
end // 
delimiter ; 

を動作するはず最後のトークンの位置にあり、この

+------+---------------------+ 
| id | address    | 
+------+---------------------+ 
| 1 | 13 mont 12c45 st | 
| 2 | 13 mont 12345 st | 
| 3 | 13 mont 12c45 45678 | 
| 4 | 56789 mont 12c45 st | 
+------+---------------------+ 

機能を与えているとして、これを返す

+------+---------------------+----------+ 
| id | address    | zipcode | 
+------+---------------------+----------+ 
| 1 | 13 mont 12c45 st | NotFound | 
| 2 | 13 mont 12345 st | 12345 | 
| 3 | 13 mont 12c45 45678 | 45678 | 
| 4 | 56789 mont 12c45 st | 56789 | 
+------+---------------------+----------+ 
関連する問題