简体   繁体   中英

Export Multiple Query Results to Single Excel File

I ran a sp in SSMS and it gathers information from 50+ databases with the exact same structure. I am pulling results such as CustomerName, NumberOfUsers and VersionofCode. When I execute the procedure, I get 50+ different result sets, all with the same columns selected. Instead of exporting these 50+ times and putting it together in a single excel sheet, I'd like to see if I can export all results to 1 excel file.

Is this possible? I would have to think there would be a way to do this as my column names match up for every database I am querying.

Any help is appreciated!

There are probably a number of ways to solve this problem. I would address the issue by attempting to merge the many result sets from your stored procedure calls into a single result set and then perform whatever output-export (to excel) that you wish to do.

Simplest method would be to use a temp table to accumulate the results from each stored proc call. You can use the "INSERT #temptable EXEC mystoredproc @param1" syntax to store the results of a stored proc.

Here's a little example I whipped up:

-- *** Create a sample stored proc that returns one result set ***
CREATE PROC spGetCompanyEmployees @pCompanyID AS INT
AS
BEGIN
    SELECT Company.CompanyName
        , Department.DepartmentName 
        , Employee.EmployeeName
    FROM Company 
        LEFT JOIN Department ON Department.CompanyID = Company.CompanyID
        LEFT JOIN Employee ON Employee.DepartmentID = Department.DepartmentID
    WHERE Company.CompanyID = @pCompanyID
END
GO


-- *** Demonstrate how to call that stored proc multiple times, 
-- *** accumulating the results in a temp table and selecting
-- *** the combined results at the end.

CREATE TABLE #ttbl
(
    CompanyName NVARCHAR(60)
    , DepartmentName NVARCHAR(60)
    , EmployeeName NVARCHAR(60)
)

INSERT  #ttbl
  EXEC spGetCompanyEmployees 1

INSERT  #ttbl
  EXEC spGetCompanyEmployees 2

SELECT * FROM #ttbl

The resulting output from that final SELECT will be a combined, single result set from both stored procedure calls.

I hope this helps.

I combined the suggestion to use a temp table with an example from this blog post that uses sys.sp_msforeachdb to iterate through databases, resulting in the following:

Create TABLE #temp
(
    DbName NVARCHAR(50),
    TableName NVARCHAR(50)
)

INSERT #temp

EXEC
    sys.sp_msforeachdb 
    'SELECT ''?'' DatabaseName, Name FROM [?].sys.Tables WHERE Name LIKE ''%sometablename%'''

Select * from #temp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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