SQL查询使数字列成为字符串

时间:2011-06-16 02:56:01

标签: sql sql-server string tsql sql-server-2008

是否可以在一个大字符串中转换一列双打:

类似的东西:

att1
----------
123.2
3.6
6.77
23.43
4.78
7.6
123.2
9.6
1.77
3.43
24.78
76.6
411.5
346.5
975.75
162.788
4.5
16.2
324.5
746.5
975.75
12.788
24.5
6.2


to

string = "
123.2,
3.6,
6.77,
23.43,
4.78,
7.6,
123.2,
9.6,
1.77,
3.43,
24.78,
76.6,
411.5,
346.5,
975.75,
162.788,
4.5,
16.2,
324.5,
746.5,
975.75,
12.788,
24.5,
6.2
";

2 个答案:

答案 0 :(得分:2)

declare @List varchar(max)

select @List = isnull(@List + ',', '') + cast(ColumnName as varchar)
from MyTable

print @List

例如:

declare @List varchar(max)

select @List = isnull(@List + ',', '') + cast(object_id as varchar)
from sys.objects

print @List

select stuff(
    (select ',' + cast(object_id as varchar)
    from sys.objects
    for xml path('')),
    1, 1, '')

答案 1 :(得分:1)

我不认为这是最好的解决方案,但我之前遇到过类似的问题。使用SQL Server,我只是将数据解析为XML字符串,然后替换为实际的XML。这将其转换为以逗号分隔的值列表。

REPLACE(
    REPLACE(
        REPLACE(
            (SELECT
                some_field AS [data()]
            FROM
                some_table
            FOR
                XML PATH ('label'))
        ,'</label><label>',',')
    ,'</label>','')
,'<label>','')