C# 在SQL Server中执行时发生CLR SplitString异常
您好,我是C#编程新手,刚刚从复制并粘贴了CLR函数,以便在SQL Server 2012中使用:C# 在SQL Server中执行时发生CLR SplitString异常,c#,sql,sql-server,clr,argumentnullexception,C#,Sql,Sql Server,Clr,Argumentnullexception,您好,我是C#编程新手,刚刚从复制并粘贴了CLR函数,以便在SQL Server 2012中使用: using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; public class CustomFunctions { [ Micr
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public class CustomFunctions
{
[
Microsoft.SqlServer.Server.SqlFunction
(
FillRowMethodName = "FillRow",
TableDefinition = "nRow int, string nvarchar(4000)"
)
]
public static IEnumerable SplitString(SqlString str, SqlString delimiter)
{
if (str.IsNull || delimiter.IsNull)
{
return null;
}
string[] values = str.Value.Split(delimiter.Value.ToCharArray());
StringPair[] results = new StringPair[values.Length];
for (int i = 0; i < values.Length; i++)
{
results[i] = new StringPair(i + 1, values[i]);
}
return results;
}
public static void FillRow(object row, ref int id, ref string value)
{
StringPair pair = (StringPair)row;
id = pair.ID;
value = pair.Value;
}
public class StringPair
{
public StringPair(int id, string value)
{
this.ID = id;
this.Value = value;
}
public int ID { get; private set; }
public string Value { get; private set; }
}
};
然后我在SQL Server中执行它:
DECLARE @string VARCHAR(256) = '1,2,3,4,5,6,7';
SELECT * FROM [dbo].[SplitString](@string, ',')
它引发异常System.ArgumentNullException:
System.ArgumentNullException:值不能为null。参数名称:
ptr System.ArgumentNullException:在
System.Runtime.InteropServices.Marshal.PtrToStringUni(IntPtr-ptr,
Int32(len)
由于我无法在当前环境中调试CLR函数,我甚至不知道哪一行会抛出该异常。可能不是您要寻找的答案,但为什么不使用本机sql函数来执行此操作呢?它会更便宜,性能也会更好,这里有一种方法:
CREATE or alter FUNCTION STRING_SPLIT2
(
@List nvarchar(max),
@Delimiter nchar(1)
)
RETURNS @t table (Item nvarchar(max))
AS
BEGIN
SET @List += @Delimiter;
;WITH a(f,t) AS
(
SELECT CAST(1 AS bigint), CHARINDEX(@Delimiter, @List)
UNION ALL
SELECT t + 1, CHARINDEX(@Delimiter, @List, t + 1)
FROM a WHERE CHARINDEX(@Delimiter, @List, t + 1) > 0
)
INSERT @t SELECT SUBSTRING(@List, f, t - f) FROM a OPTION (MAXRECURSION 0);
RETURN;
END
GO
如果您使用的是SQL Server 2017
或更高版本,则SQL Server具有内置功能
名为“STRING_SPLIT”的函数具有相同的功能:
DECLARE @string VARCHAR(256) = '1,2,3,4,5,6,7';
SELECT * FROM string_split(@string, ',')
DECLARE @string VARCHAR(256) = '1,2,3,4,5,6,7';
SELECT * FROM string_split(@string, ',')