2016-03-17 98 views
1

我以前使用過BULK INSERT,但我剛剛注意到它有跳過第一行的問題。我寧願不跳過任何東西,所以這是我一直在使用的代碼。T SQL批量插入跳過第一行有或沒有標題

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文件。思考?

回答

2

我認爲你需要再次看看你的數據的格式。也許有些無形的空間在某個地方貼合?

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 
+1

奇怪......當我沒有標題行和使用FIRSTROW = 1時,跳過第一排。只是再次嘗試使用標題行和FIRSTROW = 2,它的工作原理正確。不知道這對我有意義...但它現在會做。感謝您的貢獻。 –