在SQL中拆分长字符串

时间:2012-11-07 15:57:28

标签: sql sql-server-2008 user-defined-functions

此处建议的内联解决方案:vzczc的How do I split a string so I can access item x?仅适用于包含少于100个元素的字符串,因为递归深度的限制(并且您无法更改UDF内的限制)。

有哪些其他方法可以分割具有良好性能的长字符串?我一直在使用的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

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:1)

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

-- 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