MSFN Forum: T-SQL Shrink File - MSFN Forum

Jump to content



Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

T-SQL Shrink File Auto Shrink log files Rate Topic: -----

#1 User is offline   Taggs 

  • Taggs
  • PipPip
  • Group: Members
  • Posts: 185
  • Joined: 03-February 05

Posted 21 September 2009 - 09:08 AM

Hi,
I am trying to automate a Log Shrink File for all databases on our SQL Server (2005). I have a script that works to a fashion but I am having problems with one command.

Declare @database_name varChar(50),@database_name_temp varChar(54)
Declare database_name_CURSOR CURSOR FOR select name from sys.sysdatabases where dbid >4 order by name
OPEN database_name_CURSOR
FETCH NEXT FROM database_name_CURSOR into @database_name
While @@FETCH_STATUS = 0
Begin
 Set @database_name_temp= @database_name + '_Log'
 Use @database_name
 DBCC ShrinkFile (@database_name_temp,10)
 Backup log @database_name with Truncate_only
 DBCC ShrinkFile (@database_name_temp,10) 
 FETCH NEXT FROM database_name_CURSOR into @database_name
End
Close database_name_CURSOR;
Deallocate database_name_CURSOR


The problem is with the command Use @database_name

the error message I get is

Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '@database_name'.


If I substitute for a real Database name it works for that database (but no others obviously)


Thanks
Taggs


#2 User is offline   Taggs 

  • Taggs
  • PipPip
  • Group: Members
  • Posts: 185
  • Joined: 03-February 05

Posted 24 September 2009 - 03:54 AM

OK I have a solution (from a post on another forum)

The problem is USE looks for an Identifier

The solution is exec('use ' + @database + '; <other statement/s here>)

At the moment the job is reliant on the fact that the lodgical name is the same as the DB name

My final code looks like this

Declare @database_name varChar(50),@database_name_temp varChar(54)
Declare database_name_CURSOR CURSOR FOR select name from sys.sysdatabases where dbid >4 order by name
OPEN database_name_CURSOR
FETCH NEXT FROM database_name_CURSOR into @database_name

While @@FETCH_STATUS = 0
Begin
 Set @database_name_temp= @database_name + '_Log'
 exec('use ' + @database_name + '; DBCC ShrinkFile (' + @database_name_temp + ',10); Backup log ' + @database_name + ' with Truncate_only; DBCC ShrinkFile (' + @database_name_temp + ',10)')
 FETCH NEXT FROM database_name_CURSOR into @database_name
End
Close database_name_CURSOR;
Deallocate database_name_CURSOR

This post has been edited by Taggs: 24 September 2009 - 03:56 AM


Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users



All trademarks mentioned on this page are the property of their respective owners
Copyright © 2001 - 2011 msfn.org
Privacy Policy