将String转换为逗号分隔值

时间:2012-07-17 11:32:05

标签: sql-server-2008

我有一张表格如下

DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB'

需要输出如下,但不使用任何UDF。

Data  String
------------
SQL   S,Q,L
JOB   J,O,B

请帮我解决这个问题

4 个答案:

答案 0 :(得分:2)

当然可以:)。你也可以把它缩短......

DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB';    

With cte as
(
    Select Data, Len(Data) DataLength, 1 level
    From @t
    Union All 
    Select Data, DataLength - 1, level + 1
    From cte
    Where DataLength > 1 
),
cte2 as
(
    Select Data, SUBSTRING(Data, DataLength, 1) DataLetter, level
    From cte
),
cte3 as
(
    Select Data, 
        (
            SELECT DataLetter + ','
            FROM cte2 c
            Where c.Data = cte2.Data
            Order By level desc
            FOR XML PATH(''), TYPE

        ).value('.[1]', 'NVARCHAR(1000)') DataComa
    From cte2
    Group By Data
)
Select Data, substring(DataComa, 1, Len(DataComa) - 1) Data2
From cte3

答案 1 :(得分:1)

晚会,但这是一个稍短的版本:

DECLARE @T TABLE(Data VARCHAR(MAX));

INSERT INTO @T VALUES('SQL'),('JOB'),('FLOOB');

;WITH n AS (SELECT TOP (SELECT MAX(LEN(Data)) FROM @T) 
  n = ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects
),
t AS (SELECT n, Data, Letter = SUBSTRING(t.Data, n.n, 1) FROM n
  INNER JOIN @T AS t ON SUBSTRING(t.Data, n.n, 1) > ''
)
SELECT Data, STUFF((SELECT ',' + letter FROM t AS t2
  WHERE t2.Data = t.Data ORDER BY t2.n FOR XML PATH(''), 
  TYPE).value('.[1]', 'varchar(max)'), 1, 1, '')
FROM t GROUP BY Data;

结果:

FLOOB   F,L,O,O,B
JOB     J,O,B
SQL     S,Q,L

答案 2 :(得分:0)

使用UDF非常容易。 但是如果你想要UDF,我能想到的唯一方法就是

类似这样的事情

DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB'

select replace(replace(replace(data,'S','S,'),'Q','Q,'),'L','L,') from @T

这里你必须用替换功能替换所有26个字符。即'A'与'A','B'与'B',''Z'与'Z',

答案 3 :(得分:0)

使用我用于Initcap函数的相同方法http://beyondrelational.com/modules/2/blogs/70/posts/10901/tsql-initcap-function-convert-a-string-to-proper-case.aspx

DECLARE @T TABLE(Data VARCHAR(MAX)) 
INSERT INTO @T 
SELECT 'SQL' UNION ALL SELECT 'JOB' 

select data,
        upper(replace(replace(replace(replace(replace(replace(replace(
        replace(replace(replace(replace(replace(replace(replace(
        replace(replace(replace(replace(replace(replace(replace(
        replace(replace(replace(replace(replace(
            ' '+data ,
        ' a','a,'),' b','b,'),'c','c,'),'d','d,'),'e','e,'),'f','f,'),
        ' g','g,'),' h','h,'),'i','i,'),'j','j,'),'k','k,'),'l','l,'),
        ' m','m,'),' n','n,'),'o','o,'),'p','p,'),'q','q,'),'r','r,'),
        ' s','s,'),' t','t,'),'u','u,'),'v','v,'),'w','w,'),'x','x,'),
        ' y','y,'),' z','z,')) as splitted_data
from
    @t