Q
Problem solve Get help with specific problems with your technologies, process and projects.

How do I run a T-SQL query to loop through all databases?

Find out how to run a T-SQL query to loop through all databases.

I have a shared Microsoft SQL Server that has over 100 databases on it. The log files are getting outrageously...

large and I'm trying to conserve some disk space. Rollbacks to specific transactions aren't important. I would like to change all the databases to SIMPLE recovery mode so I can run an auto-shrink each night. Unfortunately, I can't find anything that explains how to run a T-SQL query to loop through all databases. Is this possible? If so, can you provide an example of how to do this?

Run this command:

EXEC sp_MSforeachdb @command1="print 'ALTER DATABASE ' + ('?') + ' SET RECOVERY SIMPLE'"

Then you can copy the output from this query and paste into another query window to actually change the settings. You can also remove the system databases when you select from the output, so you don't change these databases.

Do you have comments on this Ask the Expert Q&A? Let us know.

This was last published in August 2005

Dig Deeper on SQL Server Backup and Recovery

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchBusinessAnalytics

SearchDataCenter

SearchDataManagement

SearchAWS

SearchOracle

SearchContentManagement

SearchWindowsServer

Close