当前位置:编程学习 > JAVA >>

Java调用BCP导入数据到数据库解决标识列ID问题

①要导入的数据如下:
 

 
红框框的则是标识列,自动增长。
但是,我们使用了
 
bcp sportSys.dbo.competitions in %1competitions.xls -c -T >>%2import.txt
②导入数据之后,发现数据出现了问题。
 
 
可以很清晰的发现,ID变了,由此带来的问题也就可想而知了,怎么解决这个问题呢?
有人提出了下面的这种做法:
 
SET IDENTITY_INSERT tb ON--把显式值插入表的标识列中。 
INSERT INTO..... 
SET IDENTITY_INSERT tb OFF--完成之后关闭选项

这条语句使用的时候,只能一张表一张表的导入,也就失去了批量导入的意义了。
而且直接写在我们的bat文件中还会提示
SET IDENTITY_INSERT sportSys.dbo.compet 
itions on 
环境变量 IDENTITY_INSERT sportSys.dbo.competitions 没有定义 
 
经查阅文档发现,bcp已经为我们提供了一个非常好的解决方法,加上-E
这个参数,即可解决标识列的问题!
下面是-E 参数的详细介绍,
-E  
Specifies that identity value or values in the imported data file are to be used for the identity column. If -E is not given, the identity values for this column in the data file being imported are ignored, and SQL Server automatically assigns unique values based on the seed and increment values specified during table creation.  
 
If the data file does not contain values for the identity column in the table or view, use a format file to specify that the identity column in the table or view should be skipped when importing data; SQL Server automatically assigns unique values for the column. For more information, see DBCC CHECKIDENT (Transact-SQL). 
 
The -E option has a special permissions requirement. For more information, see "Remarks" later in this topic. 
 
 
如果bcp导入的时候,没有加入-E这个参数,则对于目标表中的标识列的处理则由Sql Server 自动的来处理,因此得出的ID值就不是我们想要的了。

作者:w156445045

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,