How to concatenate all columns in a select with SQL Server

后端 未结 5 916
借酒劲吻你
借酒劲吻你 2020-12-03 12:45

I need my select to have a pattern like this:

 SELECT \' \' + tbl.* + \' \' FROM table tbl;

The ideal solution wo

5条回答
  •  抹茶落季
    2020-12-03 13:37

    SQL Fiddle

    MS SQL Server 2008 Schema Setup:

    create table YourTable
    (
      ID int identity primary key,
      Name varchar(50),
    )
    
    insert into YourTable values
    ('Name 1'),
    ('Name 2'),
    ('Name 3'),
    ('Name 4'),
    ('Name 5')
    

    Query 1:

    select (
           select (
                  select ', '+T2.N.value('./text()[1]',  'varchar(max)')
                  from (
                       select T.*
                       for xml path(''), type
                       ) as T1(N)
                    cross apply T1.N.nodes('/*') as T2(N)
                  for xml path(''), type
                  ).value('substring(./text()[1], 3)',  'varchar(max)')
           for xml path('text'), type
           )
    from YourTable as T
    

    Results:

    |               COLUMN_0 |
    --------------------------
    | 1, Name 1 |
    | 2, Name 2 |
    | 3, Name 3 |
    | 4, Name 4 |
    | 5, Name 5 |
    

提交回复
热议问题