SQL Server Database does not exist sp_MSforeachdb

With SQL Server, when using the sp_MSforeachdb system stored procedure, the system displays this error “Database does not exist. Make sure that the name is entered correctly.” . The stored procedure displays the error because the database tries to access a database that does not exist in your SQL Server instance, so it’s obviously not visible in the database list using SSMS. But somehow it appears in the list with the query execution.

How to fix the SQL Server error “Database ‘Your-database name’ does not exist. Make sure that the name is entered correctly.” with sp_MSforeachdb

This issue is a classical issue with the naming of the database. There is no error in the sp_MSforeachdb system stored procedure or in the sys.sp_MSforeach_worker sp.

The solution is to check the names and rename the databases.

If the SQL Server databases names contains spaces or dashes then you can simply rename them or replace the characters by an underscore.

USE [master]

ALTER DATABASE [database name is-not-good] MODIFY NAME = Database_name_is_good_now;

To conclude, don’t use the dash and the space signs in database names. It’s technically possible to use them but in order to use built-in system stored procedures, it’s better to use only underscores. Or even better, avoir any special characters in your database object names.