Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

sql server - SQL won't insert null values with BULK INSERT

I have a CSV file and each line looks similar to this:

EASTTEXAS,NULL,BELLVILLE AREA,NULL,BELLVILLE AREA,RGP,NULL,NULL,0,NULL,NULL,NULL,1,1,PM,PM Settings,NULL,NULL

I couldn't find any examples on how NULL values were supposed to be handled when doing BULK INSERT, so I assumed that was OK.

When I try to run the BULK INSERT, it gives me this error:

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

Here's my table and what not:

CREATE TABLE #Assets
(
ParentID VARCHAR(255) NULL,
ClassificationID VARCHAR(255) NULL,
AssetID VARCHAR(255) NULL,
AssetType VARCHAR(255) NULL,
AssetName VARCHAR(255) NULL,
RepairCenterID VARCHAR(255) NULL,
LaborID VARCHAR(255) NULL,
Owner VARCHAR(255) NULL,
IsLocation VARCHAR(255) NULL,
AssetTypeDesc VARCHAR(255) NULL,
ClassificationName VARCHAR(255) NULL,
ClassificationPK INT NULL,
IsUp BIT NULL,
RequesterCanView BIT NULL,
PMCycleStartBy VARCHAR(255) NULL,
PMCycleStartByDesc VARCHAR(255) NULL,
PMCycleStartDate DATETIME NULL,
PMCounter INT NULL,
ParentPK INT NULL,
ParentName VARCHAR(255) NULL,
AssetPK INT NULL,
RepairCenterPK INT NULL,
RepairCenterName VARCHAR(255) NULL,
LaborPK INT NULL)

BULK
INSERT #Assets
FROM '\cdmsqlint01dropassets.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '
',
KEEPNULLS
)
GO

SELECT * FROM #Assets

DROP TABLE #Assets

Any ideas on what I'm doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to:

http://msdn.microsoft.com/en-us/library/ms187887.aspx

null values can be inserted by having an empty field within your file.

Example file was:

1,,DataField3
2,,DataField3

Example method of importing file keeping nulls is:

USE AdventureWorks;
GO
BULK INSERT MyTestDefaultCol2
FROM 'C:MyTestEmptyField2-c.Dat'
WITH (
    DATAFILETYPE = 'char',
    FIELDTERMINATOR = ',',
    KEEPNULLS
);
GO

Granted, this means you'll have to change your "NULL"s to "", and any empty strings you did want as empty string would be interpreted as nulls, but it might be enough to get you started? I would imagine to keep your empty string columns they would need to be changed from

field1,,field2

to

field1,"",field2

as example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...