Use master -- note that this stored procedure should be created in the master database
Go
If exists (select * From DBO. sysobjects where id = object_id (n' [DBO]. [p_compdb] ') and objectproperty (ID, n' isprocedure') = 1)
Drop procedure [DBO]. [p_compdb]
Go
Create proc p_compdb
@ Dbname sysname, -- Name of the database to be compressed
@ Bkdatabase bit = 1, -- because the log separation step may damage the database, you can choose whether to automatically Database
@ Bkfname nvarchar (260) = ''-- Name of the backup file. If this parameter is not specified, the backup file is automatically backed up to the default backup directory. The backup file name is: database name + date and time.
As
-- 1. Clear logs
Exec ('dump transaction ['+ @ dbname +'] With no_log ')
-- 2. truncate transaction logs:
Exec ('backup log ['+ @ dbname +'] With no_log ')
-- 3. compress the database file (if it is not compressed, the database file will not be reduced
Exec ('dbcc shrinkdatabase (['+ @ dbname +']) ')
-- 4. Set automatic contraction
Exec ('exec sp_dboption ''' + @ dbname + ''', ''autoshrink '', ''true ''')
-- The subsequent steps are dangerous. You can choose whether to perform these steps.
-- 5. Database Separation
If @ bkdatabase = 1
Begin
If isnull (@ bkfname, '') =''
Set @ bkfname = @ dbname + '_' + convert (varchar, getdate (), 112)
+ Replace (convert (varchar, getdate (), 108 ),':','')
Select prompt = 'Back Up the database to the default SQL Backup Directory. Backup File Name: '+ @ bkfname
Exec ('backup database ['+ @ dbname +'] to disk = ''' + @ bkfname + '''')
End
-- Separate
Create Table # T (fname nvarchiar (260), type INT)
Exec ('insert into # T select filename, type = Status & 0x40 from ['+ @ dbname +'] .. sysfiles ')
Exec ('SP _ detach_db ''' + @ dbname + '''')
-- Delete a log file
Declare @ fname nvarchar (260), @ s varchar (8000)
Declare TB cursor local for select fname from # t where type = 64
Open TB
Fetch next from TB into @ fname
While @ fetch_status = 0
Begin
Set @ s = 'del "'+ rtrim (@ fname) + '"'
Exec master .. xp_mongoshell @ s, no_output
Fetch next from TB into @ fname
End
Close TB
Deallocate TB
-- Attach a database
Set @ s =''
Declare TB cursor local for select fname from # t where type = 0
Open TB
Fetch next from TB into @ fname
While @ fetch_status = 0
Begin
Set @ s = @ s + ', ''' + rtrim (@ fname) + ''''
Fetch next from TB into @ fname
End
Close TB
Deallocate TB
Exec ('SP _ attach_single_file_db ''' + @ dbname + ''' + @ s)
Go
/* -- Call example
Exec p_compdb 'test'
--*/