SQL批量插入

问题描述 投票:2回答:1

我有一个发送给我的csv文件。我已将文件放入Notepad ++,该文件将ROWTERMINATOR显示为CRLF。这意味着我在SQL中将\ r \ n用作我的ROWTERMINATOR正确吗?

这是文件格式(每行末尾是CRLF):

2020/02/10 03:00:00,2020/02/11 02:59:59,2
101,1,5,1,7,10950,0,10950,0,1429
101,1,5,2,7,28878,5500,28878,0,0
101,1,5,3,4,9525,1200,9525,0,0
101,1,5,4,1,7686,0,7686,0,0
101,1,5,7,3,9094,1300,9094,0,0

我本质上需要从第一个单元格中获取日期,然后忽略该行的其余部分,而我已经这样做了:

SET @sql =
'BULK INSERT #date  
FROM ' + '''' + @fileName + '''' + '
WITH
(
    FIRSTROW = 1,
    LASTROW = 1,
    ROWTERMINATOR = ' + '''' + ',' + '''' + ',
    FIELDTERMINATOR = ' + '''' + ',' + '''' + ',
    CODEPAGE=' + '''' + '65001' + '''' + ',
    KEEPNULLS
)'

然后拉出剩余的5行数据,因为将所有数据都包装到一行中,所以该行不起作用:

SET @sql =
'BULK INSERT #fileColumns  
FROM ' + '''' + @fileName + '''' + '
WITH
(
    FIRSTROW = 2,
    FIELDTERMINATOR = ' + '''' + ',' + '''' + ',
    ROWTERMINATOR = ' + '''' + '\r\n' + '''' + ',
    CODEPAGE=' + '''' + '65001' + '''' + ',
    KEEPNULLS
)'

[我也尝试过使用\ n作为ROWTERMINATOR,因为我将最后四行包装在第一行中,所以它给出了最后四行。

sql sql-server bulkinsert
1个回答
0
投票

我真的不喜欢我必须这样做的方式,但是它可以起作用:

SET @sql =
'BULK INSERT #fileColumns  
FROM ' + '''' + @fileName + '''' + '
WITH
(
    FIRSTROW = 2,
    ROWTERMINATOR = ' + '''' + '\n' + '''' + ',
    CODEPAGE=' + '''' + '65001' + '''' + ',
    KEEPNULLS
)'

EXEC (@sql)

WITH Split AS (
SELECT  Column1,
        Split.value,
        ROW_NUMBER() OVER(PARTITION BY Column1 ORDER BY (SELECT NULL)) AS RowNumber
    FROM #fileColumns
    CROSS APPLY STRING_SPLIT(Column1, ',') AS Split
)

SELECT  [1] AS ProfitCenterId,
        [2] AS CheckTypeId,
        [3] AS MealPeriodId,
        [4] AS TenderId,
        [5] AS NumberOfTenders,
        [6] AS TenderAmount,
        [7] AS TipAmount,
        [8] AS ReceivedAmount,
        [9] AS BreakageAmount,
        [10] AS ChangeGiven
        FROM Split
        PIVOT
        (
            MAX(value)
            FOR RowNumber IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])
        ) AS piv

绝对不漂亮,但是可以。

© www.soinside.com 2019 - 2024. All rights reserved.