客户的数据库需要搬迁,但是当前数据库还有其它业务查询,不能断开,在搬迁的过程中,客户端不允许写入数据。
所以决定把客户端连接所使用的用户连接线程杀死,再备份后转移。
1
declare
@dbname
varchar
(
20
)
--
-杀死的连接数据库名
2
3 set @dbname = ' tempdb ' -- -设置数据库名
4
5 declare @sql nvarchar ( 500 )
6 declare @spid int -- SPID 值是当用户进行连接时指派给该连接的一个唯一的整数
7 set @sql = ' declare getspid cursor for select spid from sysprocesses where
2
3 set @dbname = ' tempdb ' -- -设置数据库名
4
5 declare @sql nvarchar ( 500 )
6 declare @spid int -- SPID 值是当用户进行连接时指派给该连接的一个唯一的整数
7 set @sql = ' declare getspid cursor for select spid from sysprocesses where
dbid=db_id(
'''
+
@dbname
+
'''
) and loginame=
''
loginuser
'''
8 -- sysprocesses 包含有关SQL Server进程的信息。
9 exec ( @sql )
10 open getspid
11
12 fetch next from getspid into @spid
13
14 while @@fetch_status <> - 1 -- 如果FETCH语句没有执行失败或此行不在结果集中。
15 begin
16 exec ( ' kill ' + @spid ) -- 终止正常连接
17 fetch next from getspid into @spid
18 end
19
20 close getspid
21 deallocate getspid
22
23
24 -- 查看活动的线程
25 -- select login_time, last_batch, hostname, loginame, * from sysprocesses
8 -- sysprocesses 包含有关SQL Server进程的信息。
9 exec ( @sql )
10 open getspid
11
12 fetch next from getspid into @spid
13
14 while @@fetch_status <> - 1 -- 如果FETCH语句没有执行失败或此行不在结果集中。
15 begin
16 exec ( ' kill ' + @spid ) -- 终止正常连接
17 fetch next from getspid into @spid
18 end
19
20 close getspid
21 deallocate getspid
22
23
24 -- 查看活动的线程
25 -- select login_time, last_batch, hostname, loginame, * from sysprocesses
--where db_id('''+@dbname+''') and loginame ='loginuser'