sql server 应用bcp进行数据导出导入

bcp 实用工具可以在 Microsoft SQL Server 实例和用户指定格式的数据文件间大容量复制数据。 使用 bcp 实用工具可以将大量新行导入 SQL Server 表,或将表数据导出到数据文件。

需要下载:https://www.microsoft.com/zh-CN/download/details.aspx?id=56567

                  https://docs.microsoft.com/zh-cn/sql/tools/bcp-utility?view=sql-server-2017

1.使用命令行 

-整个表导出(out)
bcp 数据库名.dbo.表名 out c:\currency.txt -S"数据库实例" -U"用户" -P"密码" -c
--使用SQL语句导出(queryout)
bcp "select * from 数据库名.dbo.表名" queryout c:\currency.txt -S 数据库实例 -U"用户" -P"密码" -c
 
--设置字段分隔符和行分隔符(-c -t"," -r"\n"),不想输入字段类型等请配合-c一起使用
 bcp "select * from 数据库名.dbo.表名" queryout c:\currency.txt -S 数据库实例 -U"用户" -P"密码" -c -t"," -r"\n"
 
--指定每批导入数据的行数、指定服务器发出或接收的每个网络数据包的字节数(-k -b5000 -a65535)
 bcp "select * from 数据库名.dbo.表名" queryout c:\currency.txt -S 数据库实例 -U"用户" -P"密码" -c -t"," -r"\n" -k -b5000 -a65535
 
2. --在SQL SERVER 查询分析器上执行(EXEC master..xp_cmdshell)
 
-- 允许配置高级选项 
EXEC master.sys.sp_configure 'show advanced options', 1 
-- 重新配置 
RECONFIGURE 
-- 启用xp_cmdshell 
EXEC master.sys.sp_configure 'xp_cmdshell', 1 
--重新配置 
RECONFIGURE 
 
EXEC master..xp_cmdshell 'bcp "select * from 数据库名.dbo.表名" queryout c:\currency.txt -S 数据库实例 -U"用户" -P"密码" -c'

--把SQL语句生成一个.sql文件,然后调用
--注:路径的文件夹名称中间不能有空格
exec master..xp_cmdshell 'osql -S 数据库实例 -U 用户 -P 密码 -i    C:\cmdshellTest.sql'
 
--将数据导入到currency表中
EXEC master..xp_cmdshell 'bcp 数据库名.dbo.表名 in c:\currency.txt -c -T'

--导入数据也同样可以使用-F和-L选项来选择导入数据的记录行。
EXEC master..xp_cmdshell 'bcp 数据库名.dbo.表名 in c:\currency.txt -c -F 10 -L 13 -T'

                       

猜你喜欢

转载自www.cnblogs.com/zhang1f/p/11079546.html