在 SQL Server 中执行存储过程时如何将输出保存到文件

问题描述 投票:0回答:1

我想将存储过程输出直接保存到文件中。

我已经使用了

BCP
命令,但仍然没有保存文件。

这是使用

BCP
的命令:

bcp " SELECT TOP (1000) column FROM table " queryout "D:\spoutput.csv" -S servername -U username -P password -c -T 
sql-server bcp
1个回答
0
投票

我会使用 Powershell 而不是 BCP,除非您特别需要 BCP 的某些功能。

您可以使用

Invoke-SqlCmd
执行任何您想要的任意SQL;在本例中,是一个存储过程。然后将其结果通过管道传输到
Export-Csv
(如果您想在 Powershell 中更多地使用 CSV,也可以将其通过管道传输到
ConvertTo-Csv
)。我发现您可以通过
bcp
配置输出文件的最常见操作也可以通过 powershell 完成。事实上,powershell 可以做一些
bcp
不能 的事情,例如处理字段的引用。

# the server you want to run the proc on
$serverInstance = "localhost\lemur"
# the database the proc lives on
$database = "test"
# the path where you want the output file created
$outputFile = ".\output.csv"

# NOTE: You could do this in one go; I split it into multiple lines for clarity
$results = Invoke-SqlCmd -ServerInstance $serverInstance -Database $database -Query "exec dbo.GetDatabases"
$results | Export-Csv -Path $outputFile -Delimiter '|' -NoTypeInformation
© www.soinside.com 2019 - 2024. All rights reserved.