`

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

    博客分类:
  • java
 
阅读更多

面的一篇博文讲解了调用bcp批量导出数据,对于批量导入数据则写的不怎么详细,本文再详细的介绍下一个使用技巧。对于批量导入,如果表中含有标识列,则默认会按照Sql Server 的处理方式来处理这个标识列,因此也就不是我们需要的ID值了,本文我们一起来探讨下解决方法。

①要导入的数据如下:

 

 

红框框的则是标识列,自动增长。

但是,我们使用了

 

  1. bcp sportSys.dbo.competitions in %1competitions.xls -c -T >>%2import.txt 

②导入数据之后,发现数据出现了问题。

 

 

可以很清晰的发现,ID变了,由此带来的问题也就可想而知了,怎么解决这个问题呢?

有人提出了下面的这种做法:

 

  1. SET IDENTITY_INSERT tb ON--把显式值插入表的标识列中。  
  2. INSERT INTO.....  
  3. SET IDENTITY_INSERT tb OFF--完成之后关闭选项 

这条语句使用的时候,只能一张表一张表的导入,也就失去了批量导入的意义了。
而且直接写在我们的bat文件中还会提示

  1. SET IDENTITY_INSERT sportSys.dbo.compet  
  2. itions on  
  3. 环境变量 IDENTITY_INSERT sportSys.dbo.competitions 没有定义  
  4.  

经查阅文档发现,bcp已经为我们提供了一个非常好的解决方法,加上-E

这个参数,即可解决标识列的问题!

下面是-E 参数的详细介绍,

  1. -E   
  2. 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.   
  3.  
  4. 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).  
  5.  
  6. The -E option has a special permissions requirement. For more information, see "Remarks" later in this topic.  
  7.  

 

如果bcp导入的时候,没有加入-E这个参数,则对于目标表中的标识列的处理则由Sql Server 自动的来处理,因此得出的ID值就不是我们想要的了。

本文出自 “幽灵柯南的技术blog” 博客,请务必保留此出处http://enetq.blog.51cto.com/479739/912093

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics