Having needed a split function many times in the past, I've always utilised patindex and done it the hard way…. And when it comes to nvarchar values, forget about it! So today I took a few minutes to write a SQL CLR function to do it. The function takes a string and a delimiter and returns a table of string values. Here are the instructions for those who may want to do the same thing… using System; public class CSRSplitString public static IEnumerable udfclrSplitString(SqlString InputString,SqlString Delimiter) sp_configure 'clr enabled', 1 CREATE ASSEMBLY CSRSplitString CREATE FUNCTION udfclrSplitString select *
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections;
{
[SqlFunction(FillRowMethodName = "FillRow")]
{
return InputString.Value.Split(Delimiter.Value.ToCharArray(0, 1));
}
public static void FillRow(object row, out string InputString)
{
InputString = (string)row;
InputString = InputString.Trim();
}
}
GO
RECONFIGURE
GO
FROM 'D:\<YourDLLName>.dll'
WITH PERMISSION_SET = SAFE
(@String nvarchar(4000),@Delimiter nvarchar(1))
RETURNS
TABLE (ArrayItem nvarchar(4000))
AS EXTERNAL NAME CSRSplitString.CSRSplitString.udfclrSplitString;
Where external name is MyDotNETAssembly.MyClassname.Method
from udfclrSplitString('Kristen,Patrick,Julian,Werner,Koe',',')
You should get 5 rows back …
Select a.name as DbNameOriginal,s.*
from msdb.sys.databases a cross
apply udfclrSplitString(a.name,'_') s
where a.name like '%_%'
You will need to have the function in the msdb database for this example to work
Management Reporter 2012 CU15 Hotfix 3 Now Available
10 years ago

4 comments:
Wow that's some tortured Hungarian notation there. Also, did you do any performance testing against the conventional version of this same proc? This is one that people usually have laying around already so a CLR proc would be reinventing the wheel wouldn't it?
When you say conventional I'm presuming you mean using a stored proc? Which won't help if you want to split an nvarchar.
I get an error when compiling in VS.NET saying...
The method "SplitString" in class "UserDefinedFunctions" marked as a table-valued function must define a table definition in the SqlFunction attribute.
A search has turned up this site saying that it requires defining the table in the SqlFunction attribute like this...
[SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "Value nvarchar(4000))]
Perfect...many thanks
Post a Comment