How exactly does sp_msforeachdb work behind the scenes?

First of all don't use sp_msforeachdb it has several known issues. You are better off using Aaron Bertrand's version here and here.

However it uses a cursor, dynamic SQL and a replace. You can actually look at the code by using sp_helptext.

EXEC sp_helptext sp_msforeachdb

If you use this code it will fix some of your issues.

EXEC SP_msforeachdb 'SELECT ''?'' AS Database
                 FROM [?].sys.objects
                 WHERE name like ''%aetna%''

The brackets will the specific problem you mentioned. You will however run into issues if you have a database with [ or ] in it.


Not disagreeing with anything that @Kenneth said, I should point out that the error you are encountering has nothing to do with sp_MSForEachDB. It is due to how the Database was named: it starts with a number. The rules for naming objects (not just Databases) are detailed in the MSDN page for Database Identifiers. If you follow the "Rules for Regular Identifiers" then you don't need to enclose those names in square brackets or double-quotes. But names that fall outside of those rules do need to be enclosed (always).