之前我曾经使用过BULK INSERT,但我刚刚注意到它在跳过第一行时遇到了问题。我宁愿不让它跳过任何东西,所以这是我一直在使用的代码。
IF OBJECT_ID('tempdb.dbo.#tempTable', 'U') IS NOT NULL
DROP TABLE #tempTable;
CREATE TABLE #tempTable
(
StartDate datetime,
EndDate datetime,
TransactionItemsMigrated bigint,
TransactionSizeBytes bigint,
CurrentItemsFailed bigint
)
BULK INSERT #tempTable
FROM 'C:\csv\xxxxx.csv' --change to CSV file location
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n',
TABLOCK
)
INSERT INTO Transactions
(
ProjectID,
StartTime,
EndTime,
TransactionItemsMigrated,
TransactionSizeBytes,
TransactionTimestamp,
CurrentItemsFailed
)
SELECT
4, --change to projectID
StartDate,
EndDate,
TransactionItemsMigrated,
TransactionSizeBytes,
GETDATE(), --sets TransactionTimestamp to current datetime
CurrentItemsFailed
FROM #tempTable
插入工作正常,但它跳过标题后的第一行数据。如果我取出标题并使用FIRSTROW = 1,FIRSTROW = 0,或者甚至完全注释FIRSTROW,它仍会跳过第一行。我查看了回车\ n或\ r \ n,但所有其他行都可以正常工作。我怀疑这是问题的根源,但我不确定如何将第一行拉入。源数据是一个没有应用格式的直接csv文件。想法?
答案 0 :(得分:3)
我认为您需要再次查看数据的格式。也许某些看不见的白色空间紧贴在某个地方?
IF OBJECT_ID('tempdb.dbo.#tempTable', 'U') IS NOT NULL
DROP TABLE #tempTable;
CREATE TABLE #tempTable
(
StartDate datetime,
EndDate datetime,
TransactionItemsMigrated bigint,
TransactionSizeBytes bigint,
CurrentItemsFailed bigint
)
BULK INSERT #tempTable
FROM 'D:\User\Documents\test.csv' --change to CSV file location
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n',
TABLOCK
)
SELECT * FROM #tempTable
此代码适用于此示例csv文件
StartDate,EndDate,TransactionItemsMigrated,TransactionSizeBytes,CurrentItemsFailed
2016-03-17,2016-03-17,0,1,2
2016-03-18,2016-03-17,1,1,2
2016-03-19,2016-03-17,2,1,2
2016-03-20,2016-03-17,3,1,2
使用此输出
StartDate EndDate TransactionItemsMigrated TransactionSizeBytes CurrentItemsFailed
2016-03-17 00:00:00.000 2016-03-17 00:00:00.000 0 1 2
2016-03-18 00:00:00.000 2016-03-17 00:00:00.000 1 1 2
2016-03-19 00:00:00.000 2016-03-17 00:00:00.000 2 1 2
2016-03-20 00:00:00.000 2016-03-17 00:00:00.000 3 1 2