Are you sure this is the exact same thing you ran in SSMS? It looks like it would run in just master if that's where it started.
In this part:set @SQL = 'USE ' + @name + ';'
print @SQL
exec (@SQL)
Once you execute with the exec(@SQL), the change in database context with the USE statement is no longer in effect. Check the example in the documentation and the last bullet in for the section on Self-Contained batches.
Using sp_executesql
You can see this in your script - just add select db_name() after that execute. You could pull out the other code in your cursor and just use: set @SQL = 'USE ' + @name + ';'
print @SQL
exec (@SQL)
print DB_NAME ()
It will just print print out master after each of the USE YourDatabase statements
Sue