sql server中NULL导入decimal字段时报错

时间:2023-03-08 20:17:28
sql server中NULL导入decimal字段时报错

sql server中NULL导入decimal字段时报错

在导入CSV文件时,如果decimal字段为null值,导致文本文件入库时失败。

错误现象

构造例子

新建一张表,包含decimal字段。

create table dbo.test (id smallint, subtotal decimal(20,3))
select * from dbo.test

新建一个文本文件,将部分subtotal字段值设置为NULL

id,subtotal
1,20.3
2,10.3
3,5.3
4,NULL
5,NULL

使用ssms图形工具导入

按照全局设置导入时就会报错

sql server中NULL导入decimal字段时报错

对decimal字段错误选择忽略

只要单独忽略decimal字段的错误,就可以实现对null值所在的导入

sql server中NULL导入decimal字段时报错

如此设置之后,导入就能够成功。

sql server中NULL导入decimal字段时报错

1> select * from test
2> go
id subtotal
------ ----------------------
1 20.300
2 10.300
3 5.300
4 NULL
5 NULL (5 行受影响)

使用命令进行导入

文本文件的导入方式可以参照这篇文章

不加格式文件导入

1>
2> bulk insert dbo.test
3> from 'C:\Users\camash\Desktop\test.csv'
4> with(
5> fieldterminator=',',
6> rowterminator='\r\n'
7> )
8> go
消息 4864,级别 16,状态 1,服务器 RJD08,第 2 行
第 1 行、第 1 列(id)出现大容量加载数据转换错误(类型不匹配或者字符对于指定的代码
页无效)。

指定格式文件导入

  • 创建格式文件
BCP dm01.dbo.test format nul -f d:\dump\test.fmt -t"," -c -r"\n" -T

Due to how Microsoft Windows treats text files (\n automatically gets replaced with \r\n).

结果依然报错。

按照搜索一大片网页,发现要处理这种问题只能把数据导入到临时表中,此表的decimal字段设置为字符型,导入后在进行转换。

参考此文处理http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=109242