Skip to content
View in the app

A better way to browse. Learn more.

MSFN

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

T-SQL Shrink File

Featured Replies

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

  • Author

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

Edited by Taggs

Create an account or sign in to comment

Recently Browsing 0

  • No registered users viewing this page.

Account

Navigation

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.