简体   繁体   English

如何使用SQL Server从远程数据库导出查询结果为CSV?

[英]How export query result as CSV from a remote database with SQL Server?

I'm doing the following query on a remote database: 我正在远程数据库上执行以下查询:

DECLARE @SQL varchar(max) = 
'SELECT ts, value
   FROM history
  WHERE name = ''SOME_ID''

EXEC (@SQL) AT SOME_LINKED_SERVER

So the expected output is like that: 所以预期的输出是这样的:

ts       value
----------------
ts1     value1
ts2     value2
…      …

I'm doing this query for almost 100 different names and am willing to save a different CSV for each output. 我正在为近100个不同的名称执行此查询,并且我愿意为每个输出保存不同的CSV。 I know I can do it manually by clicking with the right button on the query's output and selection “Save Result As...”, but it would take too long, specially because each query takes about 10 minutes to finish. 我知道我可以通过单击查询输出上的右键并选择“将结果保存为...”来手动完成,但这需要太长时间,特别是因为每个查询大约需要10分钟才能完成。

So I'd like to do it automatically, making the procedure export all the different CSV's after getting the data. 所以我想自动执行此操作,使程序在获取数据后导出所有不同的CSV。 My ideia is to loop the search through an array of names, do the query and export the output as a CSV. 我的想法是通过一系列名称循环搜索,执行查询并将输出导出为CSV。

How can I do that? 我怎样才能做到这一点? Before trying to loop through the array, I'm already struggling to output a CSV for a single query result. 在尝试循环遍历数组之前,我已经在努力为单个查询结果输出CSV。

Why do it one name at a time when you can do this: 为什么一次只能使用一个名称:

SELECT [ts], [value], [name]
FROM [SOME_LINKED_SERVER].[database_name].[dbo].[history] H (NOLOCK)
WHERE [name] IN (<name list>)

If you want to store the result on the local end, then insert the data into a local table and work with the data there. 如果要将结果存储在本地端,则将数据插入本地表并在其中处理数据。 Like so: 像这样:

SELECT [ts], [value], [name]
INTO [local_history]
FROM [SOME_LINKED_SERVER].[database_name].[dbo].[history] H (NOLOCK)
WHERE [name] IN (<name list>)

SELECT * FROM [local_history] -- WHERE [name] = 'SOME_ID'

Then export, either by using Save Results As..., or copy and pasting the results into Excel, and doing a Save as... (F12). 然后导出,或者使用“将结果另存为...”,或者将结果复制并粘贴到Excel中,然后执行另存为...(F12)。

Even better: if you have SSIS installed, use that to build a package that runs the query, and does the export for you. 更好的是:如果安装了SSIS,请使用它来构建运行查询的包,并为您进行导出。 SSIS can even loop through the list of names if it comes down to that. 如果归结为SSIS,SSIS甚至可以遍历名称列表。 If you don't have SSIS installed, install it, it comes with SQL Server. 如果您没有安装SSIS,请安装它,它随SQL Server一起提供。 SSIS can be made to automate this process entirely. SSIS可以完全自动化这个过程。

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

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