壓縮資料庫的通用儲存過程

2021-03-31 08:56:59 字數 2723 閱讀 8584

/*--

壓縮資料庫的通用儲存過程

壓縮日誌及資料庫檔案大小

因為要對資料庫進行分離處理

所以儲存過程不能建立在被壓縮的資料庫中

--鄒建

2004.3--*/

/*--

呼叫示例

exec p_***pdb 'test'

--*/

use master--注意,

此儲存過程要建在

master

資料庫中 go

if exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[p_***pdb]') and objectproperty(id, n'isprocedure') = 1)

drop procedure [dbo].[p_***pdb]

go

create proc p_***pdb

@dbname sysname,--

要壓縮的資料庫名

@bkdatabase bit=1,--

因為分離日誌的步驟中

,可能會損壞資料庫

,所以你可以選擇是否自動資料庫

@bkfname nvarchar(260)='' --

備份的檔名

,如果不指定

,自動備份到預設備份目錄

,備份檔案名為

:資料庫名

+日期時間 as

--1.

清空日誌

exec('dump transaction ['+@dbname+'] withno_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

壓縮資料庫日誌檔案 儲存過程

use master goset ansi nulls on goset quoted identifier on go 建立人 高公升 建立日期 2007 05 18 修改日期 2007 06 02 功能目的 收縮資料庫的日誌檔案 引數 要執行收縮的資料庫名稱,如果引數為 則收縮所有的非系統資料庫...

公司學習 通用資料庫儲存過程分頁

create procedure dbo username pageindex int,pagesize int as declare min int declare max int set min pagesize pageindex 1 1 set max pagesize pageindex ...

資料庫 儲存過程

儲存過程,stored procedure,是在大型資料庫系統中,一組為了完成特定功能的sql語句集,經編譯後儲存在資料庫中,使用者通過指定儲存過程的名字並給出引數 如果該儲存過程帶有引數 來執行它。模擬於c中的函式。mysql與sqlserver是不同的。建立儲存過程 conn getconnec...