【转】SQL Server T-SQL写文本文件

本文介绍了使用 SQL Server 创建文本文件的各种方法,包括 osql、bcp、重定向命令、sp_MakeWebTask 和 COM 对象调用等。这些方法各有特点,适用于不同场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:http://www.nigelrivett.net/SQLTsql/WriteTextFile.html

 

The are several methods of creating text files from sql server.

  • osql
  • bcp
  • redirection commands
  • sp_MakeWebTask
  • Com object calls

Remember that in all cases the path of the output file will be relative to the server - not to the client on which the application is running.

osql.
This example will just output master..sysobjects to the file c:\osqloutput.txt.

declare @cmd varchar(1000)
select @cmd = 'osql -U -P -S -Q"select * from master..sysobjects" -o"c:\osqloutput.txt" -w500'
exec master..xp_cmdshell @cmd

bcp
bcp very fast and easy to use for just dumping a table out - can be used against a view too.

master..xp_cmdshell 'bcp master..sysobjects out c:\file.bcp -S -U -P -c '

redirection commands
You will need to create the data to be output as in dynamic sql statements
The first command here creates or overwrites the file - the rest append to the file.

exec master..xp_cmdshell 'echo hello > c:\file.txt'
exec master..xp_cmdshell 'echo appended data >> c:\file.txt'
exec master..xp_cmdshell 'echo more data >> c:\file.txt'

will generate a file containing
hello
appended data
more data

sp_MakeWebTask
This is for creating html code from a query

Com object calls
Using sp_oa... system stored procedures and creating com objects or existing applications you can probably do whatevr you wish - but you should probably ask whether sql server is the right place to control this.

转载于:https://www.cnblogs.com/duanguyuan/p/4111094.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值