1

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.