views:

242

answers:

2

I have a Microsoft SQL Server 2008 with many databases and most of them have a Logs table. I would like to be able to schedule a script to run and truncate the Logs table in every one of these databases (dynamically). I imagine I have to get the name of every user database then truncate the table Logs in the databases that contain a Logs table.

The statement I ended up using is:

EXEC sp_MSForEachDB 'Use [?]; IF  EXISTS (SELECT * FROM sys.tables WHERE name = "Logs" and type="U")TRUNCATE TABLE Logs'
+7  A: 

It's a bit of hack, since the stored procedure is undocumented, but try this:

EXEC sp_MSForEachDB 'Use ?; TRUNCATE TABLE Logs'
Joel Coehoorn
+1, this is a good solution, why was there a -1 for this??
KM
It wasn't me, I am still testing.
notandy
here is a good example to run to try this out (if you don't want to truncate a table): EXEC sp_MSForEachDB 'Use ?; print db_name()'
KM
Toddler at the mouse syndrome :( I initialy read this as transaction logs you cant truncate in 2008 so it wouldnt resolve that issue.
u07ch
I testing using the statement "EXEC sp_MSForEachDB 'Use ?; SELECT * FROM Logs'" This sort of worked for a sec. and then started returning errors. (Invalid object name) I then tried the actual statement on a development system and it errors out with no changes to the DB. (Cannot find the object..) Msg 4701
notandy
I think the catch is that not every database contains the proper table.
notandy
You can add an 'if exists' guard around it.
Joel Coehoorn
Facepalm, Thanks, That took care of it.
notandy
A: 

In 2008 the easiest thing to do if if its not in production use at the time is this

Write a script that does this in dynamic sql

Alter Database <mydb> set recovery simple
go

Checkpoint
go

Alter Database <mydb> set recovery full
go
u07ch
I definitely should have picked a less ambiguous table name.
notandy
He's not looking to truncate the Transaction Log, but rather to truncate a table called Logs.
Rick