How to concatenate all columns in a select with SQL Server

后端 未结 5 901
借酒劲吻你
借酒劲吻你 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 <text>

    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 '<text>' + @s + '</text>'
    

    SQL Fiddle Example here

    -- RESULTS 
    <text>col1, col2, col3,...</text>
    

    If you need select query result set wrapped with <text> 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 ''<text>''+' + @s + ')+' + '''</text>'' FROM YourTableName')
    

    SQL Fiddle Example here

    --RESULTS
    <text>c1r1,c2r1,c3r1,...</text>
    <text>c1r2,c2r2,c3r2,...</text>
    <text>c1r3,c2r3,c3r3,...</text>
    
    0 讨论(0)
  • 2020-12-03 13:20

    I tried a more generic approach

    Create Procedure P_GetConcatColumns(@tablename varchar(200),@Seperator Varchar(20),@StartTag Varchar(20),@EndTag Varchar(20),@WhereString Varchar(400),@OrderString Varchar(400)) as
    
    
    DECLARE @TmpTableName VARCHAR(100),
            @Columns NVARCHAR(4000),
            @SQL NVARCHAR(MAX),
            @GENNAME VARCHAR(100)
    
    Select  @GENNAME='##'+Replace(Cast(NewID() as Varchar(40)),'-','')
    
    IF OBJECT_ID('tempdb.dbo.' + @GENNAME) IS NOT NULL
    BEGIN
        EXEC('DROP TABLE ' +@GENNAME);
    END
    
    
    
    
    Select @SQL='SELECT TOP 1 * INTO '+@GENNAME+' FROM ' + @tablename
    Exec (@SQL)
    
    
    
    SET @TmpTableName = 'tempdb.dbo.' + @GENNAME
    SELECT @Columns = 
        STUFF(
        (
        SELECT '+' + @Seperator + '+CAST(Coalesce(' + c.name + ','''') AS VARCHAR(MAX))' + CHAR(13)
        FROM tempdb.sys.columns c
        WHERE c.[object_id] = object_Id(@TmpTableName)
        FOR XML PATH(''),TYPE
        ).value('.','VARCHAR(MAX)')
        ,1,len(@Seperator)+2,'')
    
    --SET @SQL = N'SELECT ' +''''+ @StartTag +''''+'+'+ @Columns +''''+'+'+ @EndTag + ''' FROM ' + @tablename 
    SET @SQL = N'SELECT ''' +@StartTag+ '''+'+ @Columns +'+'''+ @EndTag + ''' FROM ' + @tablename 
    +' '+Coalesce(@WhereString,'')
    +' '+Coalesce(@OrderString,'')
    Print @SQL
    EXEC sp_executeSQL @SQL
    
    
    --ExampleCall P_GetConcatColumns 'Arten',''',''','<test>','</test>','where id>1','Order by ID desc'
    
    0 讨论(0)
  • 2020-12-03 13:24

    Try the code below:

    SELECT Stuff(
    (SELECT N', ' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
    where TABLE_NAME = 'YourTableName' FOR XML PATH(''),TYPE)
    .value('text( [1]','nvarchar(max)'),1,2,N'')
    
    0 讨论(0)
  • 2020-12-03 13:26

    IBMDB2: Create file with desired delimiter, e.g. delimiter='#|#' below
    Step1:- Run the below query, and you get the SQL statement in query_to_execute column:

    select table_name, 'select '||listagg(column_name, '||''#|#''||')||' from '||trim(table_schema)||'.'||(table_name) as query_to_execute
          from qsys2.SYSCOLUMNS                                  
         where table_name in ('YOURTABLE1', 'YOURTABLE2')                             
           and table_schema = 'YOURSCHEMA'                         
         group by table_schema, table_name
    

    Step2:- Run the query formed above to get a delimited file in SQL.

    Step3a(If running SQL from native iSeries): Move result to flat file, and import/FTP_get the flat file to other platforms.

    Step3b(If running SQL using a query tool from windows): Export the result to a file_name.xxx of your choice.

    This way you we create a CSV or a delimited file with delimiter of our choice.

    /Neeraj Kumar

    0 讨论(0)
  • 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 |
    --------------------------
    | <text>1, Name 1</text> |
    | <text>2, Name 2</text> |
    | <text>3, Name 3</text> |
    | <text>4, Name 4</text> |
    | <text>5, Name 5</text> |
    
    0 讨论(0)
提交回复
热议问题