Save output of multiple queries into file?

大城市里の小女人 提交于 2020-06-12 03:33:06

问题


I have a SQL query that I have to run against multiple (15) tables in SQL Server Management Studio.

Is it possible to save the result of multiple queries into a file? (.txt, excel sheet?)

Using union is not possible because not all tables have an equal amount of columns.

The queries look somewhat like this

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:


Try below:-

  1. Open SQL Server Management Studio
  2. Go to Tools > Options > Query Results > SQL Server > Results To Text
  3. Then on right hand side, change output format to comma delimited.
  4. Run your query and then right click on results and click save results to file.
  5. Once done rename the file from .rpt to .csv



回答2:


For those confused by the above answer (like I was, as it didn't work), you should go instead to the Query menu, look down to Results to... and then pick "to file" or whichever you want.

Change rpt to csv as the above mentions.

Be sure to re-run your queries obviously.




回答3:


If you want multiple queries result to a single file, you can follow below steps:

  1. Create view for every SQL query you have got. This is just for loading purpose.
  2. You can use Import-Export wizard in SQL Server Management Studio. Right click database > Tasks > Export Data.
  3. In the Wizard choose SQL Server database as source and Excel file as destination.
  4. Choose export multiple tables and select views as the source, and in the target excel, a separate sheet will be mentioned as the destination in the excel file.
  5. Go to next steps in the wizard and Finish the wizard
  6. Now the views data will be loaded to separate sheets in the target excel
  7. Now, you can remove the views, as you dont need them

all the above things can be done inside SSMS.

There are many other options to load data from Multiple ways to export data from SSMS into separate files



来源:https://stackoverflow.com/questions/40509859/save-output-of-multiple-queries-into-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!