declare @databasename nvarchar (100)
--Define cursors and assign values to get all the online database Name
Declare getdatabasecursor cursor for select name from master.sys.databases where state_desc= ' online '
--You must open the cursor before using the cursor
Open Getdatabasecursor
--Using the FETCTH statement to get the data, a fetch statement can put a record in the specified variable at one time to achieve shrink per db effect
FETCH NEXT from Getdatabasecursor to @databasename
While @ @FETCH_STATUS = 0
Begin
declare @RecoveryModel nvarchar (20)
declare @sql nvarchar (100)
DECLARE @logfileid int
Select @RecoveryModel = Cast (DATABASEPROPERTYEX (name, ' RECOVERY ') as varchar) from master: sysdatabases where name [email protected]
IF @RecoveryModel <> ' simple '
Begin
EXEC (' ALTER DATABASE ' [email protected] + ' SET RECOVERY simple ')
End
declare @dsql nvarchar (200)
Set @dsql =n ' Select @logfileid = file_id from ' + @databasename + N '. sys.database_files where type_desc = ' LOG '
EXEC sp_executesql @dsql, N ' @logfileid int output ', @logfileid output
EXEC (' use ' [email protected]+ ' DBCC shrinkfile (' [email protected]+ ') ')
FETCH NEXT from Getdatabasecursor to @databasename
End
--At the end of the cursor operation, do not forget to close the cursor so that the system frees the resources that the cursor occupies
CLOSE Getdatabasecursor
--Delete cursor
Deallocate getdatabasecursor
The compressed database log file used by the cursor