sql server - Within While Loop how to execute "Use [database name] Go" -


i need shrink log file every database weekly. writing while loop query loop each database. don't think allowed following:

declare @database_id int declare @database varchar(255) declare @log varchar(255) declare @cmd varchar(500)  while (select count(*) #logfiles processed = 0) > 0 begin       set @database_id = (select min(database_id) #logfiles processed = 0)     set @database = (select name #logfiles database_id = @database_id , [type] = 0)     set @log = (select name #logfiles database_id = @database_id , [type] = 1)      select @database, @log          set @cmd = 'use ' + @database         exec(@cmd)      set @cmd = 'dbcc shrinkfile (' + @log + ');'      exec(@cmd)      update #logfiles      set processed = 1     database_id = @database_id  end 

or there way so?

thanks

as mentioned in multiple comments, really, really, isn't idea. shrinking these files can grow again next week wasted effort and, since log file autogrow events can't take advantage of instant file initialization (since, unlike data file allocations, log file allocations have zeroed out before use), can impact end user performance in ways can't predict or control.

that said, ditch #temp table , cursor while loop. technically still uses loop concatenate it's easier set , at.

declare @sql nvarchar(max); set @sql = n'';  select @sql = @sql + n'   use ' + quotename(db) + ';   print db_name();   checkpoint; -- since know simple recovery   dbcc shrinkfile(' + quotename(f) + ') no_infomsgs;' (   select db_name(database_id), name    sys.master_files    database_id > 4 , [type] = 1    -- , lower(name) not in (n'reportserver', n'reportservertempdb') ) x(db, f);  print @sql; --exec sp_executesql @sql; 

check out print output. when you're satisfied it's going think, uncomment exec , run again.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -