Need to export fields containing linebreaks as a CSV from SQL Server

后端 未结 9 546
野的像风
野的像风 2020-12-28 13:49

I\'m running a query from SQL Server Management Studio 2005 that has an HTML file stored as a a string, e.g.:

SELECT html 
FROM table 

Thi

相关标签:
9条回答
  • 2020-12-28 14:05

    If you are using Visual Studio, Server Explorer is an alternative solution. You can correctly copy & paste the results from its grid.

    0 讨论(0)
  • 2020-12-28 14:05

    According to the closest thing to a standard we have, a correctly formatted CSV-file should quote fields containing either the separator (most often ; or ,) or a linebreak.

    SQL Server Management Studio can do that, but amazingly it doesn't have this option enabled by default. To enable, go to Tools → Options → Query Results → Results to Grid and check "Quote strings containing list separators when saving .csv results"

    0 讨论(0)
  • 2020-12-28 14:09

    i know this is very old question and has been answered now but this should help as well:

     SELECT html
     From table
     For Xml Auto, Elements, Root('doc') 
    

    it should spit out an xml and then you can import that xml into excel

    0 讨论(0)
  • 2020-12-28 14:10

    found this useful but I was still hitting problems as my field was type text so I cast the text as varchar(8000) and above replace works like a charm

    REPLACE(REPLACE(CAST([TEXT FIELD] AS VARCHAR(8000)), CHAR(10), ' '), CHAR(13), ' ') AS 'Field Name',
    
    0 讨论(0)
  • 2020-12-28 14:11

    SQL Server Import and Export Data tool, FTW!

    Start -> Programs -> Microsoft SQL Server -> Import and Export Data

    Sample query:

    select *
    from (
    select 'Row 1' as [row], 'Commas, commas everywhere,' as [commas], 'line 1
    line 2
    line 3' as [linebreaks]
    
    union all 
    
    select 'Row 2' as [row], 'Nor any drop to drink,' as [commas], 'line 4
    line 5
    line 6' as [data]
    ) a
    

    CSV output:

    "row","commas","linebreaks"
    "Row 1","Commas, commas everywhere,","line 1
    line 2
    line 3"
    "Row 2","Nor any drop to drink,","line 4
    line 5
    line 6"
    

    Disclaimer: You may have to get creative with double-quotes in the data. Good luck!

    0 讨论(0)
  • 2020-12-28 14:17

    I know how old this is, but I found it and others might, as well. You might want to take Martijn van Hoof's answer one step further and remove possible tabs (char(9)) in addition to carriage return(13) and line feed(10).

    SELECT REPLACE(REPLACE(REPLACE(mycolumn, CHAR(9), ''), CHAR(10), ''), CHAR(13), '') as 'mycolumn' FROM mytable
    
    0 讨论(0)
提交回复
热议问题