Help in Formatting without mentioning column name in SQL

Kenny Gua 431 Reputation points
2023-01-25T18:15:20.3533333+00:00

Hi, How I can get the following desired result without mentioning column's name in the query.

Select * from country

CCode CName CPost CDest CSET CPOS CJOH

001 AU L1 RE 1 2 CEN

Desired Result:

('001','AU','L1','RE','1','2','CEN')

SQL Server Other
{count} votes

Accepted answer
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2023-01-26T04:30:17.07+00:00

    This can be done through SSIS (Import/Export Wizard from SSMS).

    Export table data from your database to a text file you defined.

    Choose no header row for the text file (uncheck the box: Column names in the first row) and with text qualifier you choose (single quote).

    You can run the package immediately or save it for later run.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 26,586 Reputation points
    2023-01-25T22:23:00.5233333+00:00

    Hi @Kenny Gua,

    Please try the following solution.

    It is using XML and XQuery to tokenize all columns in a row without specifying their names. Very flexible.

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (CCode CHAR(3), CName CHAR(2), CPost CHAR(2), CDest CHAR(2), CSET INT, CPOS INT, CJOH CHAR(3));
    INSERT @tbl (CCode, CName, CPost, CDest, CSET, CPOS, CJOH) VALUES
    ('001', 'AU', 'L1', 'RE', 1, 2, 'CEN');
    -- DDL and sample data population, end
    
    SELECT t.*
    	, result = '(''' + REPLACE(c.query('data(/root/r/*)').value('.', 'VARCHAR(128)')
    		, SPACE(1), ''',''') + ''')'
    FROM @tbl AS t
    CROSS APPLY (SELECT t.* FOR XML PATH('r'), TYPE, ROOT('root')) AS t1(c);
    
    

    Output

    ('001','AU','L1','RE','1','2','CEN')

    3 people found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.