use master -- , master
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, --
@bkdatabase bit=1, -- , ,
@bkfname nvarchar(260)='' -- , , , : +
as
--1.
exec('DUMP TRANSACTION ['+@dbname+'] WITH NO_LOG')
--2. :
exec('BACKUP LOG ['+@dbname+'] WITH NO_LOG')
--3. ( ,
exec('DBCC SHRINKDATABASE(['+@dbname+'])')
--4.
exec('EXEC sp_dboption '''+@dbname+''',''autoshrink'',''TRUE''')
-- ,
--5.
if @bkdatabase=1
begin
if isnull(@bkfname,'')=''
set @bkfname=@dbname+'_'+convert(varchar,getdate(),112)
+replace(convert(varchar,getdate(),108),':','')
select =' SQL , :'+@bkfname
exec('backup database ['+@dbname+'] to disk='''+@bkfname+'''')
end
--
create table #t(fname nvarchar(260),type int)
exec('insert into #t select filename,type=status&0x40 from ['+@dbname+']..sysfiles')
exec('sp_detach_db '''+@dbname+'''')
--
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_cmdshell @s,no_output
fetch next from tb into @fname
end
close tb
deallocate tb
--
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
/*--
exec p_compdb 'test'
--*/