Wednesday, August 26, 2009

Execute sp_msforeachdb by excluding the system databases

For executing a query against each database, we can use either dynamic SQL (search my other posts for info on that) or use undocumented stored procedure sp_msforeachdb. It is particularly helpful when we want to do this against multiple databases.

The other challenge in using this is excluding the system databases if we want the query to be run just against the user databases. Use the below sql statements to accomplish that. Consider executing a sql statement of sp_addrole 'rolename' against each database on just the user databases.

EXEC master..sp_MSForeachdb
'USE [?]
IF DB_ID(''?'') > 4
exec sp_addrole ''rolename'''

Similar commands like above can be used to force an update statistics on all the tables in a given database:

EXEC sp_MSForEachTable  "update statistics ? with fullscan"

6 comments:

  1. Renting a car is usually a less-than-exciting experience when traveling. Getting the keys to a bland four door is nothing to write home about. What many do not realize is that any vacation or business trip can be an adventure with a car hire. Luxury Car Rental Coimbatore

    No matter the destination, having the keys to an exotic car is a thrill. Even the gas station can be fun when fellow customers notice the beauty at the pump. A car that totals more than many people's mortgage is sure to turn heads wherever it goes. Just the sound of the engine will catch the attention of admirers as you fly by.

    Self drive car Bangalore

    ReplyDelete
  2. BLCK Luxury - Bangalore | Luxury Car Rental Bangalore | Luxury Taxi Bangalore | Self Drive Cars in Bangalore

    Luxury Car Rental Bangalore

    ReplyDelete

Failed to obtain the resource handle for cluster resource with name or ID 'xxxxxxxxxxxxxxx' error on Availability Group databases

We recently had failures for our Backup Maintenance Plan (performing T-Log backups) and it would fail with the below error message: Message ...