Splitting of comma separated values [duplicate]

纵然是瞬间 提交于 2019-12-31 03:43:04

问题


I have some columns with 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


回答1:


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



回答2:


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)



回答3:


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,',')


来源:https://stackoverflow.com/questions/5487961/splitting-of-comma-separated-values

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