sql server 内置ETL工具学习(一) BCP篇

sql server 内置ETL工具学习

常用的导入方式:bcp, BULK INSERT,OPENROWSET和 SSIS。

BCP

BCP全称BULK COPY PROGRAM

有以下特点:

  • 命令行工具
  • 导出为文本文件

在异构数据库之间迁移 数据时,这个一个比较通用的方法,因为基本上所有的数据库都支持文本文件。

命令参考文档@MSDN

导出一张表

导出数据文件

bcp AdventureWorks2012.HumanResources.Employee OUT d:dumpEmployee.txt -c"char" -t"|" -r
 -T 

其中 -c表示导出用的字符类型,默认为char
-t表示字段分隔符
-r表示换行符
-T表示使用本地操作系统认证

bcp AdventureWorks2012.HumanResources.Employee OUT d:dumpEmployee.txt -c"char" -t"|" -r"
" -U"sa" -P"sql2015" -S"RJD08"

其中-U表示用户名
-P表示密码
-S表示服务器名

导出数据格式

bcp AdventureWorks2012.HumanResources.Employee format nul -f d:dumpEmployee_format.fmt -t"|" -c -r"
" -T

其中-f 表示导出的是format文件

数据导入

新建表结构

导入时需要新建目标表结构,使用select * into创建方式。

use AdventureWorks2012
go

select * into HumanResources.Employee_temp
from HumanResources.Employee where 1=2;

select * from HumanResources.Employee_temp;

执行导入

使用bcp

命令: bcp …in 格式: -f format_file

BCP AdventureWorks2012.HumanResources.Employee_temp in d:dumpEmployee.txt -c -f d:dumpEmployee_format.fmt -T

BULK insert

可以在ssms中执行

DELETE HumanResources.Employee_temp
GO
SELECT COUNT(*) FROM HumanResources.Employee_temp
GO
BULK INSERT HumanResources.Employee_temp
    FROM 'd:dumpEmployee.txt'
	WITH (FORMATFILE = 'd:dumpEmployee_format.fmt');
GO
SELECT COUNT(*) FROM HumanResources.Employee_temp
GO

OPENROWSET 大容量行集提供程序

同样是在ssms中执行

DELETE HumanResources.Employee_temp
GO
SELECT COUNT(*) FROM HumanResources.Employee_temp
GO
INSERT INTO HumanResources.Employee_temp
    SELECT *
	  FROM OPENROWSET(BULK 'd:dumpEmployee.txt',
	  FORMATFILE='d:dumpEmployee_format.fmt'
	  ) as t1;
GO
SELECT COUNT(*) FROM HumanResources.Employee_temp
GO

其它

bcp也可以在ssms中执行,可以用以下命令实现。

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO
原文地址:https://www.cnblogs.com/shenfeng/p/4498237.html