简体   繁体   English

如何将链接服务器上运行的存储过程的输出发送到 csv 文件中?

[英]How to send the output of a stored procedure running on a linked server into a csv file?

I am using SQL Server 2014 and I have the following T-SQL query running on my local PC:我正在使用 SQL Server 2014,并且在我的本地 PC 上运行了以下 T-SQL 查询:

USE [MyDatabase]

EXEC [xxx.yyy.10.23].[Emp_LIVE].[dbo].[procBIInterfaceEmployee]

[xxx.yyy.10.23] is a linked server. [xxx.yyy.10.23]是链接服务器。 When I execute this T-SQL code, it runs fine and returns the expected results.当我执行此 T-SQL 代码时,它运行良好并返回预期结果。

I would like to wrap the above codes into a new T-SQL query that would write the results into a csv file on my local PC.我想将上述代码包装到一个新的 T-SQL 查询中,该查询会将结果写入本地 PC 上的 csv 文件中。

Searching StackOverflow.com for a solution, I have landed on these 2 questions:在 StackOverflow.com 上搜索解决方案,我发现了以下两个问题:

  1. Creating a CSV file in a SQL Server stored procedure 在 SQL Server 存储过程中创建 CSV 文件
  2. How to write using BCP to a remote SQL Server? 如何使用 BCP 写入远程 SQL Server?

So, I came up with the following (based on the answers from the above 2 questions):所以,我想出了以下内容(基于上述 2 个问题的答案):

DECLARE @string AS NVARCHAR(4000)

SELECT @string = 'BCP "exec [xxx.yyy.10.23].[Emp_LIVE].[dbo].[procBIInterfaceEmployee]" QUERYOUT c:\testfolder\empdata.csv -c -T -t, -S"xxx.yyy.10.27\BI-SQL"'

EXEC master.dbo.xp_cmdshell @string

xxx.yyy.10.27\\BI-SQL is the remote server where [MyDatabase] is hosted. xxx.yyy.10.27\\BI-SQL是托管[MyDatabase]的远程服务器。 BI-SQL is the instance of that server. BI-SQL是该服务器的实例。

Running my new set of code, I get the following errors:运行我的新代码集,我收到以下错误:

SQLState = S1000, NativeError = 0 SQLState = S1000,NativeError = 0
Error = [Microsoft][ODBC Driver 11 for SQL Server]Unable to open BCP host data-file错误 = [Microsoft][ODBC Driver 11 for SQL Server]无法打开 BCP 主机数据文件
NULL空值

How do I move forward with this?我该如何向前推进?

Try this:尝试这个:

  1. Insert your sp result in a local table将您的 sp 结果插入本地表
  2. and then export from your local table.然后从本地表导出。

USE [MyDatabase]
GO

CREATE TABLE [dbo].[procBIInterfaceEmployee]( --whats in the table )

INSERT INTO [dbo].[procBIInterfaceEmployee] EXEC [xxx.yyy.10.23].[Emp_LIVE].[dbo].[procBIInterfaceEmployee]

EXEC master.dbo.xp_cmdshell 'BCP "[MyDatabase].[dbo].[procBIInterfaceEmployee]" OUT c:\testfolder\empdata.csv -c -T -t, -S"LOCALHOST" '

Note: if you have instance, you will need to do -S"LOCALHOST\\SQLEXPRESS"注意:如果你有实例,你需要做 -S"LOCALHOST\\SQLEXPRESS"

See the bcp page for all parameters.有关所有参数,请参阅 bcp 页面。 https://docs.microsoft.com/en-us/sql/tools/bcp-utility https://docs.microsoft.com/en-us/sql/tools/bcp-utility

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM