这篇 MSDN 文章描述了如何在高层次上实现这一点:
您不能将事务日志数据从一个日志文件移动到另一个以清空事务日志文件。要从事务日志文件中删除非活动事务,必须截断或备份事务日志。当事务日志文件不再包含任何活动或非活动事务时,可以从数据库中删除该日志文件。
这篇博文展示了将完成此任务的实际 T-SQL:
USE master
IF DB_ID('rDb') IS NOT NULL DROP DATABASE rDb
GO
CREATE DATABASE rDb
ON
PRIMARY
( NAME = N'rDb', FILENAME = N'C:\rDb.mdf' , SIZE = 50MB ,
FILEGROWTH = 1024KB )
LOG ON
(NAME = N'rDb_log2', FILENAME = N'C:\rDb_log2.ldf', SIZE = 3MB,
FILEGROWTH = 2MB)
,(NAME = N'rDb_log3', FILENAME = N'C:\rDb_log3.ldf', SIZE = 3MB,
FILEGROWTH = 2MB)
,(NAME = N'rDb_log4', FILENAME = N'C:\rDb_log4.ldf', SIZE = 3MB,
FILEGROWTH = 2MB)
GO
ALTER DATABASE rDb SET RECOVERY FULL
BACKUP DATABASE rDb TO DISK = 'C:\rDb.bak' WITH INIT
CREATE TABLE rDb..t(c1 INT IDENTITY, c2 CHAR(100))
INSERT INTO rDb..t
SELECT TOP(15000) 'hello'
FROM syscolumns AS a
CROSS JOIN syscolumns AS b
--Log is now about 46% full
DBCC SQLPERF(logspace)
--Check virtual log file layout
DBCC LOGINFO(rDb)
--See that file 4 isn't used at all (Status = 0 for all 4's rows)
--We can remove file 4, it isn't used
ALTER DATABASE rDb REMOVE FILE rDb_log4
--Check virtual log file layout
DBCC LOGINFO(rDb)
--Can't remove 3 since it is in use
ALTER DATABASE rDb REMOVE FILE rDb_log3
--What if we backup log?
BACKUP LOG rDb TO DISK = 'C:\rDb.bak'
--Check virtual log file layout
DBCC LOGINFO(rDb)
--3 is still in use (status = 2)
--Can't remove 3 since it is in use
ALTER DATABASE rDb REMOVE FILE rDb_log3
--Shrink 3
USE rDb
DBCC SHRINKFILE(rDb_log3)
USE master
--... and backup log?
BACKUP LOG rDb TO DISK = 'C:\rDb.bak'
--Check virtual log file layout
DBCC LOGINFO(rDb)
--3 is no longer in use
--Can now remove 3 since it is not in use
ALTER DATABASE rDb REMOVE FILE rDb_log3
--Check explorer, we're down to 1 log file
--See what sys.database_files say?
SELECT * FROM rDb.sys.database_files
--Seems physical file is gone, but SQL Server consider the file offline
--Backup log does it:
BACKUP LOG rDb TO DISK = 'C:\rDb.bak'
SELECT * FROM rDb.sys.database_files
--Can never remove the first ("primary") log file
ALTER DATABASE rDb REMOVE FILE rDb_log2
--Note error message from above