No functions, no Split_String. Use XML to split string into different fields by delimiter [duplicate]

不羁岁月 提交于 2019-12-11 16:05:52

问题


I have a string like this that doesn't have a consistent format and needs to be broken into fields by the ':' delimiter

  1:35410:102001001:102001:10:1

'STRING_SPLIT' is not a recognized built-in function name in my version of SQL Server

Any other suggestions? Thanks in advance!


回答1:


here is an example of a TVF that I use quite often. What it will do is take in a delimited string value and the value of the delimiter and return a table containing the split values.

CREATE FUNCTION [dbo].[UDF_GetTableFromList]
(
    @LIST varchar(max), 
    @DELIMITER char(1)= ','
)

RETURNS @RETURN_TABLE TABLE (Param varchar(4000))

AS
BEGIN

Declare @POS int,
    @PIECE varchar(4000)

Set @LIST = ltrim(rtrim(@LIST)) + @DELIMITER
Set @POS = charindex(@DELIMITER, @LIST, 1)

-- parse the string into a table
if REPLACE(@LIST, @DELIMITER, '') <> ''
begin

WHILE @POS > 0
    begin

    SET @PIECE = LTRIM(RTRIM(LEFT(@LIST, @POS - 1)))
    IF @PIECE <> ''
        begin

        INSERT INTO @RETURN_TABLE (param) VALUES (CAST(@PIECE AS varchar(4000)))

        end

    SET @LIST = RIGHT(@LIST, LEN(@LIST) - @POS)
    SET @POS = CHARINDEX(@DELIMITER, @LIST, 1)

    END
End
RETURN
END
GO

execution example would be

select * from [dbo].[UDF_GetTableFromList]('a,b,c,d',',')

and that would yield

in your particular case it would look something like this

select * from [dbo].[UDF_GetTableFromList](' 1:35410:102001001:102001:10:1',':')

and yield the following



来源:https://stackoverflow.com/questions/50068426/no-functions-no-split-string-use-xml-to-split-string-into-different-fields-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!