SQL Server 2005+ 使用 CLR 来分割字符串

·

1 min read

前两天我发了一个使用 CTE 分割字符串的方法,效率虽然比旧的 CHARINDEX 高一些,但是比起 CLR 速度还是差了很多,今天我就发下使用 CLR 来分割字符串的方法

public class UserFunction 

{ 

     \[SqlFunction(Name = "CLR\_SplitStringToIntTable", TableDefinition = "Id INT", FillRowMethodName = "FillRow")\] 

     public static IEnumerable SplitStringToIntTable(SqlString str) 

     { 

         return str.Value.Split(new char\[\] { ',' }, StringSplitOptions.RemoveEmptyEntries); 

     } 

     public static void FillRow(object row, out int id) 

     { 

         id = Convert.ToInt32((string)row); 

     } 

}

把上面的 C# 代码编译后放到 SQL 服务器,然后到 SQL 管理器里面建立程序集,再建立一个新的函数

CREATE FUNCTION CLR\_SplitStringToIntTable 
 (    
     @Str NVARCHAR(MAX) 
 ) 
 RETURNS TABLE (Id INT) 
 AS EXTERNAL NAME SQLServerCLR.UserFunction.SplitStringToIntTable; 
 GO

效率对比我就不贴了,我这里提高的速度可不是一点。