SQL Server convert select a column and convert it to a string

前端 未结 10 518
礼貌的吻别
礼貌的吻别 2020-12-05 05:28

Is it possible to write a statement that selects a column from a table and converts the results to a string?

Ideally I would want to have comma separated values.

10条回答
  •  再見小時候
    2020-12-05 05:32

    You can use the following method:

    select
    STUFF(
            (
            select ', ' + CONVERT(varchar(10), ID) FROM @temp
            where ID<50
    group by ID for xml path('')
            ), 1, 2, '') as IDs
    

    Implementation:

    Declare @temp Table(
    ID int
    )
    insert into @temp
    (ID)
    values
    (1)
    insert into @temp
    (ID)
    values
    (3)
    insert into @temp
    (ID)
    values
    (5)
    insert into @temp
    (ID)
    values
    (9)
    
     select
    STUFF(
            (
            select ', ' + CONVERT(varchar(10), ID) FROM @temp
            where ID<50
    group by ID for xml path('')
            ), 1, 2, '') as IDs
    

    Result will be:

提交回复
热议问题