码迷,mamicode.com
首页 > 其他好文 > 详细

BCP 数据的导入和导出

时间:2016-06-22 01:46:08      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:

BCP 命令的参数很多,使用 -h 查看参数帮助信息,参数是区分大小写的

技术分享

 

使用BCP命令导出和导入数据常用的参数如下

bcp {[[database_name.][schema_name].]{table_name | view_name} | "query"}

{in | out | queryout}  数据文件

[-c 字符类型]  | [-w 宽字符类型]
[-t 字段终止符]    [-r 行终止符]
[-i 输入文件]       [-o 输出文件]       
[-S 服务器名称]   [-U 用户名]           [-P 密码]
[-T 可信连接]
[-k 保留NULL值]

-c 使用char类型做为存储类型,没有前缀且以"\t"做为字段分割符,以"\n"做为行分割符。

-w 和-c类似,只是当使用Unicode字符集拷贝数据时使用,且以nchar做为存储类型。如果 -c 和 -w 同时指定,那么 -w 将覆盖 -c。

-t field_term 指定column分割符,默认是"\t"。

-r row_term 指定row分割符,默认是"\n"。

-S server_name[ \instance_name] 指定要连接的SQL Server服务器的实例,如果未指定此选项,BCP连接本机的SQL Server默认实例。如果要连接某台机器上的默认实例,只需要指定机器名即可。

-U login_id 指定连接SQL Sever的用户名。

-P password 指定连接SQL Server的用户名密码。

-T 指定BCP使用信任连接登录SQL Server。如果未指定-T,必须指定-U和-P。

-k 指定空列使用null值插入,而不是这列的默认值。

 

一,使用bcp 将整个table中的数据导出到txt或csv文档中

bcp db_study.dbo.sales out D:\test.txt -S . -U sa -P sa -t \t -w 
bcp db_study.dbo.sales out D:\test.csv
-S . -U sa -P sa -t , -w

二,使用 query statement 将查询结果导出到txt 或 csv文档中

1,配置SQL Server,允许运行 xp_cmdshell 命令

-- 允许配置高级选项  
EXEC master.sys.sp_configure show advanced options, 1  
-- 重新配置  
RECONFIGURE  
-- 启用xp_cmdshell  
EXEC master.sys.sp_configure xp_cmdshell, 1  
--重新配置  
RECONFIGURE

否则,SQL Server 会抛出错误信息

SQL Server 阻止了对组件“xp_cmdshell”的 过程“sys.xp_cmdshell”的访问,因为此组件已作为此服务器安全配置的一部分而被关闭。系统管理员可以通过使用 sp_configure 启用“xp_cmdshell”。有关启用“xp_cmdshell”的详细信息,请搜索 SQL Server 联机丛书中的“xp_cmdshell”。

2,使用  xp_cmdshell 命令运行BCP命令,将数据导出

EXEC master..xp_cmdshell bcp "SELECT [Store] ,[Item] ,[Color] ,[Quantity] FROM [db_study].[dbo].[Inventory]" queryout D:\test.txt -S . -U sa -P sa -t "\t" -w 

EXEC master..xp_cmdshell bcp "SELECT [Store] ,[Item] ,[Color] ,[Quantity] FROM [db_study].[dbo].[Inventory]" queryout D:\test.csv -S . -U sa -P sa -t "," -w 

3,使用  xp_cmdshell 命令,也可以将整个Table的数据导出

EXEC master..xp_cmdshell bcp [db_study].[dbo].[Inventory] out D:\test.txt -S . -U sa -P sa -t "\t" -w 

EXEC master..xp_cmdshell bcp [db_study].[dbo].[Inventory] out D:\test.csv -S . -U sa -P sa -t "," -w 


三,将数据导入到SQL Server

CREATE TABLE [dbo].[Inventory_LoadIn]
(
    [Store] [varchar](2) NULL,
    [Item] [varchar](20) NULL,
    [Color] [varchar](10) NULL,
    [Quantity] [int] NULL
)

1,使用BCP,将txt文档中的数据导入到table [dbo].[Inventory_LoadIn] 中

bcp [db_study].[dbo].[Inventory_LoadIn] in D:\test.txt -S . -U sa -P sa -t "\t" -w 

bcp [db_study].[dbo].[Inventory_LoadIn] in D:\test.csv -S . -U sa -P sa -t "," -w 

2,使用xp_cmdshell 命令执行bcp,将数据导入到数据库table中

EXEC master..xp_cmdshell bcp [db_study].[dbo].[Inventory_LoadIn] in D:\test.txt -S . -U sa -P sa -t "\t" -w 

EXEC master..xp_cmdshell bcp [db_study].[dbo].[Inventory_LoadIn] in D:\test.csv -S . -U sa -P sa -t "," -w 


参考文档:

使用BCP导出导入数据

 

BCP 数据的导入和导出

标签:

原文地址:http://www.cnblogs.com/ljhdo/p/5605488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!