拆分逗号分隔值

时间:2011-03-30 14:50:28

标签: sql sql-server sql-server-2005 tsql ssms

我有一些以逗号分隔的值的列。例如

A

as,ad,af,ag

我的经理希望输出看起来像这样:


A

as                          

ad          

af          

ag  

所有这些应该在一行之内。我想我们需要使用一些换行符。

您好我们可以使用char(13)+ char(10)替换。这个也有用......

谢谢, Shashra

3 个答案:

答案 0 :(得分:6)

您可以创建一个用户定义的UDF,如下所示。然后,只需从另一个查询中传入逗号分隔列表,它将返回一个表,其中每个值都在一个单独的行中。

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

答案 1 :(得分:6)

不使用用户定义函数

进行检查
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)

答案 2 :(得分:-2)

您希望使用字符串拆分功能,例如找到here的功能。

创建此功能后,您可以:

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