How to concatenate all columns in a select with SQL Server

后端 未结 5 928
借酒劲吻你
借酒劲吻你 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:11

    Any number of columns for a given tablename; If you need column names wrapped with

    DECLARE @s VARCHAR(500)
    
    SELECT @s =  ISNULL(@s+', ','') + c.name   
    FROM  sys.all_columns c join sys.tables  t 
                ON  c.object_id = t.object_id
    WHERE t.name = 'YourTableName'
    
    SELECT '' + @s + ''
    

    SQL Fiddle Example here

    -- RESULTS 
    col1, col2, col3,...
    

    If you need select query result set wrapped with then;

    SELECT @S =  ISNULL( @S+ ')' +'+'',''+ ','') + 'convert(varchar(50), ' + c.name    FROM 
           sys.all_columns c join sys.tables  t 
           ON  c.object_id = t.object_id
    WHERE t.name = 'YourTableName'
    
    
    EXEC( 'SELECT ''''+' + @s + ')+' + ''''' FROM YourTableName')
    

    SQL Fiddle Example here

    --RESULTS
    c1r1,c2r1,c3r1,...
    c1r2,c2r2,c3r2,...
    c1r3,c2r3,c3r3,...
    

提交回复
热议问题