简体   繁体   English

CSV的SQL Server换行符

[英]SQL Server line break for CSV

I am trying to write a query in CSV format, it is below: 我正在尝试以CSV格式编写查询,如下所示:

SELECT SUBSTRING
(
    (
        SELECT ',' + [symbol], + ',' + [date] + ',' + [price]
        FROM csvFormatTable
        FOR XML PATH('')
    )
    ,2,200000
) 
AS CSV

and it mostly gives the correct result apart from the ',' at the end of the line but I do want to replace it with a line break. 除了行末的','以外,它通常都能给出正确的结果','但我确实想用换行符代替它。 I've seen CHAR(10) and similar stuff like that but it does not give a line break but instead a '#x0D' . 我看过CHAR(10)和类似的东西,但它没有换行,而是'#x0D' The result of the query above is what I have (without the char(10) stuff) below: 上面查询的结果是我下面的内容(没有char(10)的东西):

symbol,date,price,mikeCode,2019-04-10,50,mikeCode,2019-04-11,200,mikeCode,2019-04-12,10,

Where as it should be: 应该在哪里:

symbol,date,price
mikeCode,2019-04-10,50
mikeCode,2019-04-11,200
mikeCode,2019-04-12,10

It needs the line break so it can be readable as a CSV. 它需要换行符,以便可以将其读取为CSV。

Assuming you're on SQL Server 2016- then use (N)CHAR(13) and (N)CHAR(10) . 假设您使用的是SQL Server 2016,则使用(N)CHAR(13)(N)CHAR(10) You'll then need to use TYPE , to avoid the escaping of the characters, and then value to get the values out. 然后,您需要使用TYPE ,以避免转义字符,然后使用value将值取出。

SELECT STUFF((SELECT ',' + CHAR(13) + CHAR(10) + [symbol] + 
                     ',' + [date] + ',' + [price]
             FROM csvFormatTable
             FOR XML PATH(''),TYPE).value('.','varchar(MAX)'),1,3,'') AS CSV;

If you are on SQL Server 2017+, you can use STRING_AGG 如果您使用的 SQL Server 2017+,则可以使用STRING_AGG

SELECT STRING_AGG(CHAR(13) + CHAR(10) + ',' + [symbol] + ',' + [date] + ',' + [price],CHAR(13) + CHAR(10))
FROM csvFormatTable --Untested

db<>fiddle db <>小提琴

Thanks to @Larnu I changed the settings in my SMSS (link on how to do this is here): How to correctly insert newline in nvarchar 感谢@Larnu,我更改了SMSS中的设置(有关如何执行此操作的链接在此处): 如何在nvarchar中正确插入换行符

And I just changed my query around a bit to get the wanted results to 我只是略微更改了查询以获取所需的结果

    DECLARE @SQL NVARCHAR(MAX)
    SET @SQL =
    '
        DECLARE @test NVARCHAR(MAX)
        SET @test = (SELECT STRING_AGG(CHAR(10) + [symbol] + '','' + [date] + '','' + [price], CHAR(13) ) FROM csvFormatTable)
        SELECT @test
    '

EXEC(@SQL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM