2013-02-11 35 views
1

獲取房屋或公寓號,我有以下SQL CLR C#UDF:SQL CLR C#用戶定義的函數 - 從地址

141A, Some Street Avenue 
4b, St Georges Street 
16E Test Avenue 

using System; 
using System.Data; 
using System.Data.SqlClient; 
using System.Data.SqlTypes; 
using Microsoft.SqlServer.Server; 
using System.Collections; 
using System.Text; 

public partial class UserDefinedFunctions 
{ 
    [Microsoft.SqlServer.Server.SqlFunction] 
    public static SqlString clrFn_GetDigits(string theWord) 
    { 

     if (theWord == null) { theWord = ""; } 
     string newWord = ""; 

     char[] KeepArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\\', '/', '-', ' '}; 


     foreach (char thischar in theWord) 
     { 
      foreach (char keepchar in KeepArray) 
      { 
       if (keepchar == thischar) 
       {  
        newWord += thischar; 
       }  
      } 
     } 

     return (SqlString)(newWord.Trim()); 
    } 
} 

除了像下面的地址這個偉大的工程,到目前爲止

我想讓我的函數返回141A,4b和16E

任何想法?

+0

您需要一些邏輯來檢查下一個字符 – CR41G14 2013-02-11 10:52:31

回答

1

我沒有測試過下面的代碼,但沿着這些線路的東西,一些錯誤檢查將需要到位,以保證轉換不會失敗,但這個解決方案爲您提供了你所需要的

char[] KeepArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\\', '/', '-', ' ' }; 


     foreach (char thischar in theWord) { 

      if (KeepArray.Contains(thischar)) { 

       newWord += thischar; 
      } 
      else if (Char.IsLetter(thischar) && newWord.Length > 0){ 

       try { 
        if (Char.IsDigit((Convert.ToChar(newWord.Substring(newWord.Length - 1, 1))))) { 
         newWord += thischar; 

        } 

       } 
       catch { 

       } 
      } 

     } 
+0

優秀的東西CR41G14!奇蹟般有效! – 2013-02-11 12:05:14