0

此处建议的内联解决方案:如何拆分字符串以便可以访问项目 x?由于递归深度的限制(并且您不能更改 UDF 内的限制),vzczc 仅适用于包含少于 100 个元素的字符串。

还有其他分割长字符串的方法吗?我一直在使用的 UDF(不是内联的)非常慢:

CREATE FUNCTION [dbo].[fn_ParseDelimitedStrings](@String nvarchar(MAX), @Delimiter char(1))
RETURNS @Values TABLE
(
 RowId int Not Null IDENTITY(1,1) PRIMARY KEY
,Value nvarchar(255) Not Null
)
AS
BEGIN
    DECLARE  @startPos smallint
        ,@endPos smallint

    IF (@String = '')
    RETURN

    IF (RIGHT(@String, 1) != @Delimiter)
        SET @String = @String + @Delimiter
    SET @startPos = 1
    SET @endPos = CharIndex(@Delimiter, @String)
    WHILE @endPos > 0
    BEGIN
        INSERT @Values(Value)
        SELECT LTRIM(RTRIM(SUBSTRING(@String, @startPos, @endPos - @startPos)))
        -- remove the delimiter just used
        SET @String = STUFF(@String, @endPos, 1, '')
        -- move string pointer to next delimiter
        SET @startPos = @endPos
        SET @endPos = CHARINDEX(@Delimiter, @String)
    END
    RETURN
END
4

2 回答 2

1

您可以MAXRECURSION在调用函数时使用提示来消除只能拆分少于 100 个元素的字符串的问题,因此使用您使用的链接中的示例可以调用:

-- CREATE A STRING TO SPLIT WITH OVER 100 DELIMITERS
DECLARE @s VARCHAR(1000) = 'a'

SELECT  @s = @s + ',a'
FROM    master..spt_values
WHERE   type= 'p'
AND     number BETWEEN 1 AND 150

--SPLIT LONG STRING
SELECT  *
FROM    dbo.splitString(@s, ',')
OPTION (MAXRECURSION 0) -- NO LIMIT
于 2012-11-07T16:42:29.920 回答
1

不确定这是否会为您提供与您自己的示例相同的性能(可能会),但请尝试我正在使用的一个:

 CREATE FUNCTION [dbo].[UDF_Split]
 (
     @InputParam VARCHAR(4000),
     @delimiter CHAR(1)
 ) 
 RETURNS @tSplit TABLE (
 ItemValue VARCHAR(255)
 ) 
 AS

 BEGIN

-- Declares --
--------------

-- Variables.
DECLARE @ItemValue VARCHAR(255)


-- Initialize --
----------------

-- Make sure it has a trailing comma.
IF RIGHT(@InputParam, 1) <> @delimiter SELECT @InputParam = @InputParam + @delimiter 


-- Put values separated by delimiter in a string to a table as records.
WHILE CHARINDEX(@delimiter, @InputParam) <> 0
BEGIN 
    SELECT @ItemValue = CONVERT(VARCHAR(255), SUBSTRING(@InputParam, 1, CHARINDEX(@delimiter , @InputParam) -1))


    if DATALENGTH(@ItemValue) = 0
        SELECT @InputParam = SUBSTRING(@InputParam,2, len(@InputParam) - 1)
    else
    begin
        SELECT @InputParam = SUBSTRING(@InputParam, DATALENGTH(RTRIM(@InputParam)) - ((DATALENGTH(RTRIM(@InputParam)) - DATALENGTH(RTRIM(@ItemValue))) - 2), 4000) 

        INSERT  @tSplit 
        SELECT  CONVERT(VARCHAR(255), @ItemValue)
    end     


END 

-- Return --
------------
RETURN
END 
于 2012-11-07T16:05:39.117 回答