壓縮一條資料庫語句如下:
CREATE Procedure [dbo].[sp_Compress]
AS
BEGIN
DECLARE @db_name varchar(200)
set @db_name='dangjiae' --資料庫名
DUMP TRANSACTION @db_name WITH NO_LOG
BACKUP LOG @db_name WITH NO_LOG
DBCC SHRINKDATABASE(@db_name)
END
sql server 2005 壓縮執行個體下所有資料庫檔案及記錄檔 語句
--01.get all database name
SELECT DBNAME = DB_NAME(s_mf.database_id) INTO #DN
FROM
sys.master_files s_mf
WHERE
s_mf.state = 0 and -- ONLINE
HAS_DBACCESS(DB_NAME(s_mf.database_id)) = 1 -- Only look at databases to which we have access
GROUP BY s_mf.database_id
ORDER BY 1
--02.use cursor to fetch db name
-----02.01 declare cursor
DECLARE cur CURSOR FOR
SELECT DBNAME FROM #DN
-----02.02 open cursor & declare var
OPEN cur
DECLARE @DbName VARCHAR(200)
-----02.03 loop db bane
FETCH NEXT FROM cur into @DbName
WHILE(@@FETCH_STATUS=0)
BEGIN
print 'shrinking ' + @DbName + ' ...'
-------02.04 only shink log file
exec(
'
declare @dn varchar(200);
declare @ln varchar(210);
select @dn = name from '+@DbName+'.dbo.sysfiles where fileid=1
select @ln = name from '+@DbName+'.dbo.sysfiles where fileid=2
use ['+ @DbName + '] backup log ['+ @DbName +'] with no_log dbcc shrinkfile (@ln)
'
)
-------02.04 shink db file & log file
-- dbcc SHRINKDATABASE (@DbName)
print @DbName + ' done'
FETCH NEXT FROM cur INTO @DbName
END
-----02.05 colse cursor
CLOSE cur
DEALLOCATE cur
-----03.drop temp table
DROP TABLE #DN
-------------------------------
測試伺服器的sql和日誌經常就太大了,寫一個預存程序,然後job定期執行,避免磁碟空間浪費