问题
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:-
- Open SQL Server Management Studio
- Go to Tools > Options > Query Results > SQL Server > Results To Text
- Then on right hand side, change output format to comma delimited.
- Run your query and then right click on results and click save results to file.
- 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:
- Create view for every SQL query you have got. This is just for loading purpose.
- You can use Import-Export wizard in SQL Server Management Studio. Right click database > Tasks > Export Data.
- In the Wizard choose SQL Server database as source and Excel file as destination.
- 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.
- Go to next steps in the wizard and Finish the wizard
- Now the views data will be loaded to separate sheets in the target excel
- 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