拆分逗号分隔值

Sha*_*sra 1 sql t-sql sql-server ssms sql-server-2005

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

一个

as,ad,af,ag
Run Code Online (Sandbox Code Playgroud)

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


一个

as                          

ad          

af          

ag  
Run Code Online (Sandbox Code Playgroud)

所有这些都应该排在一排.我想我们需要使用一些换行符.

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

谢谢,Shashra

DCN*_*YAM 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
Run Code Online (Sandbox Code Playgroud)


bvr*_*bvr 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)
Run Code Online (Sandbox Code Playgroud)