patternsqlModerate
sp_msforeachdb in a stored procedure does not work well
Viewed 0 times
storedsp_msforeachdbprocedureworkdoeswellnot
Problem
I'm facing strange behavior.
Here's how to reproduce: in an instance with multiple databases (SQL Server 2016 in my case), create that stored procedure (in
Then call that stored procedure with:
As you will see, it will only return data for some of the databases but not all (3 out of 11 in my case).
What is happening?
Here's how to reproduce: in an instance with multiple databases (SQL Server 2016 in my case), create that stored procedure (in
master in my case):create procedure dbo.Strange WITH EXECUTE AS owner
as
begin
exec sp_MSforeachdb 'select''?''';
end;Then call that stored procedure with:
Exec master.dbo.StrangeAs you will see, it will only return data for some of the databases but not all (3 out of 11 in my case).
What is happening?
Solution
sp_MSforeachdb has lots of known issues.
If you follow the link, you'll get to a post by Aaron Bertrand that details them, and also provides an alternate solution.
If you follow the link, you'll get to a post by Aaron Bertrand that details them, and also provides an alternate solution.
Context
StackExchange Database Administrators Q#171554, answer score: 13
Revisions (0)
No revisions yet.