开发者

Splitting of comma separated values [duplicate]

开发者 https://www.devze.com 2023-02-21 00:07 出处:网络
This question already has answers here: T-SQL: Opposite to string concatenation - how to split string into multiple records [duplicate]
This question already has answers here: T-SQL: Opposite to string concatenation - how to split string into multiple records [duplicate] (11 answers) Closed 8 years ago.

I have some columns with 开发者_StackOverflow中文版comma-separated values. For example

A

as,ad,af,ag

My manager wants the output looks like this:


A

as                          

ad          

af          

ag  

All these should come under one row. I guess we need to use something line break.

Hi can we use replace with char(13)+char(10) something. This one also works...

Thanks, Shashra


You can create a user defined UDF like the one shown below. Then, just pass in the comma separated list from another query and it will return a table with each value in a separate row.

CREATE FUNCTION [dbo].[fnSplitStringAsTable] 
(
    @inputString varchar(MAX),
    @delimiter char(1) = ','
)
RETURNS 
@Result TABLE 
(
    Value varchar(MAX)
)
AS
BEGIN
    DECLARE @chIndex int
    DECLARE @item varchar(100)

    -- While there are more delimiters...
    WHILE CHARINDEX(@delimiter, @inputString, 0) <> 0
        BEGIN
            -- Get the index of the first delimiter.
            SET @chIndex = CHARINDEX(@delimiter, @inputString, 0)

            -- Get all of the characters prior to the delimiter and insert the string into the table.
            SELECT @item = SUBSTRING(@inputString, 1, @chIndex - 1)

            IF LEN(@item) > 0
                BEGIN
                    INSERT INTO @Result(Value)
                    VALUES (@item)
                END

            -- Get the remainder of the string.
            SELECT @inputString = SUBSTRING(@inputString, @chIndex + 1, LEN(@inputString))
        END

    -- If there are still characters remaining in the string, insert them into the table.
    IF LEN(@inputString) > 0
        BEGIN
            INSERT INTO @Result(Value)
            VALUES (@inputString)
        END

    RETURN 
END


Check this without using User Defined Function

DECLARE @param VARCHAR(MAX)
SET @param = 'as,ad,af,ag'

SELECT Split.a.value('.', 'VARCHAR(100)') AS ColName  
FROM  
(
     SELECT CONVERT(XML, '<M>' + REPLACE(ColName, ',', '</M><M>') + '</M>') AS ColName  
     FROM  (SELECT @param AS ColName) TableName
 ) AS A CROSS APPLY ColName.nodes ('/M') AS Split(a)


You want to use a string splitting function, like the one found here for example.

Once you've created this function, you can:

select string as A
    from YourTable
        cross apply dbo.fnParseStringTSQL(A,',')
0

精彩评论

暂无评论...
验证码 换一张
取 消