If need to do something to all your databases there is a stored proc for you. Its called sp_msforeachdb.
This will loop though all your databases and perform a command for you. It’s similar to the foreach table sp I wrote about here.
There is one parameter @command.
Let’s get right to an example.
EXECUTE sp_msforeachdb ‘USE ? IF DB_NAME() NOT IN(”master”,”msdb”,”tempdb”,”model”) BACKUP DATABASE ? TO DISK = ”G:?.bak, WITH INIT”’
The ? gets replaced with the database name.
So that will backup any user database to the the G: drive.
This can simplify any looping code you have.