sp_msforeachdb in a stored procedure does not work well
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.