将存储过程的结果集直接写入文本文件,从存储过程内部。

huangapple go评论55阅读模式
英文:

Writing the result set of a stored procedure directly int a textfile from within the stored procedure

问题

I want to use a stored procedure to write out the summary of an income table into a text file.

我想使用存储过程将收入表的摘要写入文本文件。

I have created a stored procedure that takes two integer arguments (month and year) and prints out the result on SSMS.

我已创建一个存储过程,它接受两个整数参数(月份和年份),并在SSMS上打印出结果。

I don't want to go through the manual option of exporting the result to text.

我不想手动选择将结果导出为文本的选项。

Below is the structure of the stored procedure (I am using the AdventureWorks database here as an illustration, but my stored procedure has exactly the same structure):

以下是存储过程的结构(我在这里使用AdventureWorks数据库作为示例,但我的存储过程具有完全相同的结构):

begin
	set nocount on
	declare
	@monthSTR nvarchar(2), @yearSTR nvarchar(4), @selectList nvarchar(200)
	set @monthSTR = CONVERT(nvarchar(2),@month)
	set @yearSTR = CONVERT (nvarchar(4), @year)
	set @selectList = 'SELECT*FROM AdventureWorks.Sales.SalesOrderDetail WHERE DATEPART(MONTH, ModifiedDate)= '
	+@monthSTR + 'AND '+ 'DATEPART(YEAR, ModifiedDate)='+@yearSTR

	EXEC sp_executesql @selectList
end

我希望结果直接写入文本文件,而不是显示在SSMS上。

英文:

I want to use a stored procedure to write out the summary of a an income table into a text file.

I have created a stored procedure that takes two integer arguments (month and year) and print out the result on SSMS. I don't want to go through the manual option of exporting result to text. Below is the structure of the stored procedure (I am using adventureworks database here as an illustration, but my stored procedure is exactly of the same structure):

create proc monthlySummary(@month int, @year int) as
begin
	set nocount on
	declare
	@monthSTR nvarchar(2), @yearSTR nvarchar(4), @selectList nvarchar(200)
	set @monthSTR = CONVERT(nvarchar(2),@month)
	set @yearSTR = CONVERT (nvarchar(4), @year)
	set @selectList = 'SELECT*FROM AdventureWorks.Sales.SalesOrderDetail WHERE DATEPART(MONTH, ModifiedDate)= '
	+@monthSTR + 'AND '+ 'DATEPART(YEAR, ModifiedDate)='+@yearSTR
	

	EXEC sp_executesql @selectList
end

I want the result to be written out directly on a text file instead of being displayed on SSMS.

答案1

得分: 1

另一种解决方法是使用SQLCMD,如下所示:

SQLCMD -S server -d database -E -Q "EXEC dbo.monthlySummary" -o out.txt

它连接到服务器,执行查询并创建txt文件。文件格式(标题、列分隔符等)可以使用命令行开关-w、-h、-s进行自定义。

希望这有所帮助。

英文:

Another solution is to use SQLCMD as in the following:

SQLCMD -S server -d database -E -Q "EXEC dbo.monthlySummary" -o out.txt

It connects to the server, executes the query and creates the txt file. File formats (header, column separator,.. ) can be customized with command line switches -w -h -s.

hope this helps.

huangapple
  • 本文由 发表于 2023年5月26日 12:01:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定