2013-02-11 45 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