Looping through a Database

Tags:
Looping
Servers
SQL Server
http://searchsqlserver.techtarget.com/expert/KnowledgebaseAnswer/0,289625,sid87_gci1111272_mem1,00.html In the above article, it shows how to loop through each database. My question is, how would I loop through each database so that I can then use the sp_foreachtable? I am trying to use the following on each database on a server. “execute sp_MSforeachtable @command1='DBCC DBREINDEX ([?], '''', 100)'”

Answer Wiki

Thanks. We'll let you know when a new response is added.

If you are using SQL 2005 or newer you can next sp_MSforeachtable within sp_MSforeachdb. If you are using SQL 2000 or older you’ll need to use a cursor outside the sp_MSforeachtable.

Something like this should do the trick.
<pre>declare @db sysname, @sql varchar(4000)
declare cur CURSOR FOR SELECT name from sysdatabases where name <> ‘tempdb’
open cur
fetch next from cur into @db
while @@FETCH_STATUS = 0
begin
set @sql = ‘use ‘ + @db + ‘
exec sp_MSforeachtable ”DBCC DBREINDEX ([?], ””””, 100)”’
exec (@sql)
fetch next from cur into @db
end
close cur
deallocate cur</pre>

Discuss This Question:  

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
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

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
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

Thanks! We'll email you when relevant content is added and updated.

Following