将多个查询的输出保存到文件中?

Save output of multiple queries into file?

我有一个 SQL 查询,我必须 运行 针对 SQL Server Management Studio 中的多个 (15) 表。

是否可以将多次查询的结果保存到一个文件中? (.txt, excel sheet?)

无法使用 union,因为并非所有表都具有相同数量的列。

查询看起来有点像这样

select *
from tableA
where main_id in (select id from maintable where date is null and status ='new')

select *
from tableB
where main_id in (select id from maintable where date is null and status ='new')

select *
from tableC
where main_id in (select id from maintable where date is null and status ='new')

select *
from tableD
where main_id in (select id from maintable where date is null and status ='new')

select *
from tableE
where main_id in (select id from maintable where date is null and status ='new')

尝试以下:-

  1. 打开SQL Server Management Studio
  2. 转到工具 > 选项 > 查询结果 > SQL 服务器 > 结果到文本
  3. 然后在右侧,将输出格式更改为逗号分隔。
  4. 运行 您的查询,然后右键单击结果并单击将结果保存到文件。
  5. 完成后将文件从 .rpt 重命名为 .csv

转到“查询”菜单 >“结果到”...然后选择“到文件”或任何您想要的。 将 rpt 扩展名更改为 csv.

请务必重新运行您的查询。

如果您希望多个查询结果到一个文件,您可以按照以下步骤操作:

  1. 为每个 SQL 查询创建视图。这只是为了加载目的。
  2. 您可以在 SQL Server Management Studio 中使用导入-导出向导。右键单击数据库 > 任务 > 导出数据。
  3. 在向导中选择 SQL 服务器数据库作为源,选择 Excel 文件作为目标。
  4. 选择导出多个表和 select 视图作为源,在目标 excel 中,单独的 sheet 将作为 excel 中的目标提及文件。
  5. 转到向导中的后续步骤并完成向导
  6. 现在,视图数据将加载到目标 excel
  7. 中的单独 sheets
  8. 现在,您可以删除视图,因为您不需要它们

以上所有事情都可以在 SSMS 中完成。

还有许多其他选项可以从 Multiple ways to export data from SSMS into separate files

加载数据