将日期变量从文本文件读取到sql server表时出错

时间:2014-02-24 11:18:16

标签: sql-server bulkinsert

我正在尝试将记事本中的CSV数据存入我的数据库,但是我遇到了转换错误。 我得到了类似的错误信息,但在很长时间后研究问题时出现了不同的问题。错误讯息:

Msg 4864, Level 16, State 1, Line 3
Bulk load data conversion error (type mismatch or invalid character for the specified  codepage) for row 1, column 4 (HireDate).
Msg 4832, Level 16, State 1, Line 3
Bulk load: An unexpected end of file was encountered in the data file.
Msg 7399, Level 16, State 1, Line 3
The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did  not give any information about the error.
Msg 7330, Level 16, State 2, Line 3
Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".    

文件路径:'c:\ Student.txt'。
Student.txt的示例内容: 'wbrema','Milo','2012-02-15','2012-02-15'

db script:

CREATE TABLE [dbo].[Person](
[PersonID] [varchar](50) NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[HireDate] [date] NOT NULL,
[Enrollment Date] [datetime] NOT NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED 
(
    [PersonID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

2 个答案:

答案 0 :(得分:2)

首先:为您添加值为" PersonID" (或使其自动增量)。

第二:从CVS中删除引用。你的行应该是:

100,wbrema,Milo,2012-02-15,2012-02-15

现在,使用声明:

BULK
INSERT Person
FROM 'c:\Student.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)

...您应该能够导入数据。

答案 1 :(得分:0)

按照

的行创建原始数据的保留表
CREATE TABLE [dbo].[RAW_Person]
(
[PersonID] [varchar](50) NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[HireDate] [varchar](50) NULL,
[Enrollment Date] [varchar](50) NULL
) 

BULK将数据插入该表

然后执行文本到日期转换,作为最终插入

的一部分
INSERT INTO 
Person (PersonID, FirstName, LastName, HireDate, [Enrollment Date])
SELECT PersonID, FirstName, LastName, 
CONVERT(date,     [HireDate],        120), 
CONVERT(datetime, [Enrollment Date], 120)
FROM RAW_Person

我使用了格式化代码120(ODBC数据格式),但您可能需要一些其他值来查找帮助文件/ MSDN中的CONVERT函数以获取更多信息

成功完成后,您可以摆脱保留表数据

TRUNCATE TABLE [dbo].[RAW_Person]

或者如果你再也不这样做了

DROP TABLE [dbo].[RAW_Person]