当前位置: 移动技术网 > IT编程>数据库>MSSQL > SQL Server Bulk Insert 只需要部分字段时的方法

SQL Server Bulk Insert 只需要部分字段时的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

铁道兵家园网,儿童毛衣编织视频,长深高速地图

根据一般做法的话,导出部分字段时没有办法生成格式化xml文件,所以导入时就没有办法格式化导入数据。

我想到两点,1.手工修改格式化xml文件,2.创造一个能生成格式化xml文件的中间对象。

在msdn中寻找方法时,突然想到可以使用视图来做中间对象,于是就搭一个测试下。以下是测试记录:

复制代码 代码如下:

use master
go
create database [db_test]
go
use db_test
go
create table dbo.t_test(
id [int] identity(1,1) not null,
code varchar(10) ,
name varchar(100) ,
memo nvarchar(500) ,
memo2 ntext ,
primary key (id)
)
go
--上面创建的表是源数据表,下面创建是要导入数据的表,只有源表的三个字段
select code, name,memo into dbo.t_test2 from dbo.t_test where 1=2

--需求就是把表t_test中的code,name导入到t_test2。
--接下来,就是生成导入目标表的格式化xml文件,可是msdn上说只能生成某个对象的格式化xml文件。
--只好建立一个中间对象来达到目的,这里我创建的是一个视图。
--视图只包含需要导入的字段
create view v_test
as
select code,name from dbo.t_test2
--然后就是bcp操作
exec sp_configure 'show advanced options', 1;
reconfigure;
exec sp_configure 'xp_cmdshell', 1;
exec sp_configure 'show advanced options', 0;
reconfigure;
go
exec master..xp_cmdshell 'bcp db_test.dbo.v_test format nul -f c:/v_test_fmt.xml -x -c -t -s mypc\mydb'
go
exec master..xp_cmdshell 'bcp "select code, name from db_test.dbo.t_test" queryout c:/t_test.data -f c:/v_test_fmt.xml -t -s mypc\mydb'
go

--格式化文件和数据文件都有了,就成了.
bulk insert db_mgr.dbo.v_t1
from n'c:/t_test.data'
with
(
formatfile = n'c:/v_test_fmt.xml'
)
go
exec sp_configure 'show advanced options', 1;
reconfigure;
exec sp_configure 'xp_cmdshell', 0;
exec sp_configure 'show advanced options', 0;
reconfigure;
go
drop database db_test
go

环境是sql2005。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网