Sqlcmd

--附加
EXEC sp_attach_db @dbname = '数据库名称',
    @filename1 = 'MDF路径',
    @filename2= 'LOG路径'

--分离数据库
USE master

declare @dbname varchar(20) 
set @dbname='数据库名称'     ---这是数据库名称 
 
declare @sql nvarchar(500) 
declare @spid int--SPID 值是当用户进行连接时指派给该连接的一个唯一的整数 
set @sql='declare getspid cursor for
select spid from sysprocesses where dbid=db_id('''+@dbname+''')' 
exec (@sql) 
open getspid 
fetch next from getspid into @spid 
while @@fetch_status<>-1--如果FETCH 语句没有执行失败或此行不在结果集中。 
begin 
exec('kill '+@spid)--终止正常连接 
fetch next from getspid into @spid 
end 
close getspid 
deallocate getspid 


EXEC sp_detach_db @dbname = '数据库名称'

--清理LDF
declare @db nvarchar(20)
set @db='数据库名称'

dump transaction @db with no_log
backup log @db with no_log

dbcc shrinkdatabase(@db)

原文地址:https://www.cnblogs.com/hoperboy/p/2014394.html