sql批量插入生成的密钥

时间:2018-05-08 12:13:02

标签: sql-server csv tsql insert bulkinsert

我定义了一个具有唯一对象(生成)

的表
CREATE TABLE Table1(
    Id bigint   IDENTITY PRIMARY KEY
    ,Version    VARCHAR(10) NOT NULL
    ,Date       DATE  NOT NULL
    ,Code       VARCHAR(10) NOT NULL);
INSERT INTO Table1(Version,Date,Code) VALUES ('1.0','2018-04-16','8615');
INSERT INTO Table1(Version,Date,Code) VALUES ('1.0','2018-04-16','2285');
INSERT INTO Table1(Version,Date,Code) VALUES ('1.0','2018-04-16','11625');

现在我有一个.csv。包含更多信息的文件。我想使用像

这样的BULK INSERT
BULK INSERT Table1 
FROM 'C:\test.csv' 
WITH (
    FIELDTERMINATOR = ','
    ,ROWTERMINATOR = '\n'
    )

输入文件包含:

    1.0,2018-04-16,240061
    1.0,2018-04-17,3435
    1.0,2018-04-18,2143
    1.0,2018-04-19,44
    1.0,2018-04-20,2453
    1.0,2018-04-01,2012
    1.0,2018-04-22,123
    1.0,2018-04-23,9887
    1.0,2018-04-30,57
    1.0,2018-05-1,576
    1.0,2018-05-8,35
    1.0,2018-05-9,867
    1.0,2018-05-10,555
....

运行BULK INSERT语句会导致错误

Msg 4864, Level 16, State 1, Line 1
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 1 (Id).
Msg 4864, Level 16, State 1, Line 1
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 2, column 1 (Id).

将大量数据从csv插入de table的最佳方法是什么? (超过10000行)

1 个答案:

答案 0 :(得分:1)

尝试指定列名称,如

BULK INSERT Table1 (Version,Date,Code)
FROM 'C:\test.csv' 
WITH (
FIELDTERMINATOR = ','
,ROWTERMINATOR = '\n'
)