--查询所有SQL用户的连接信息(可显示IP) if object_id('p_getlinkinfo','P')is not null drop proc p_getlinkinfo go create proc p_getlinkinfo @dbname sysname=null, --要查�的����烀�,默�J表示所有 @includeip bit=0 --是否�@示IP信息 as begin declare @dbid int set @dbid=db_id(@dbname) if object_id('tempdb..#tb')is not null drop table #tb if object_id('tempdb..#ip')is not null drop table #ip create table #tb (id int identity(1,1), dbname sysname, hostname nchar(128), loginname nchar(128), net_address nchar(12), net_ip nvarchar(15), prog_name nchar(128)) insert into #tb(hostname,dbname,net_address,loginname,prog_name) select distinct hostname, db_name(dbid), net_address, loginame, program_name from master..sysprocesses where hostname!=''and(@dbid is null or dbid=@dbid) if @includeip=0 goto lb_show --不�@示IP declare @sql varchar(500),@hostname nchar(128),@id int create table #ip(hostname nchar(128),a varchar(200)) declare tb cursor local for select distinct hostname from #tb open tb fetch next from tb into @hostname while @@fetch_status=0 begin set @sql='ping '+@hostname+' -a -n 1 -l 1' insert #ip(a) exec master..xp_cmdshell @sql update #ip set hostname=@hostname where hostname is null fetch next from tb into @hostname end update #tb set net_ip=left(a,patindex('%:%',a)-1) from #tb a inner join (select hostname,a=substring(a,patindex('Ping statistics for %:%',a)+20,20) from #ip where a like'Ping statistics for %:%')b on a.hostname=b.hostname lb_show: select id, dbname, hostname, loginname, net_address, net_ip, prog_name from #tb end go exec p_getlinkinfo @dbname='DB_WIP',@includeip=1
上文转自:
http://bbs.csdn.net/topics/330182710#r_64221203
下文转自:
http://ryxxlong.iteye.com/blog/1045273
问题:
在SQL Server中备份/还原/分离/脱机/删除指定数据库时, 如果有其他用户正在使用此数据库时, SQL Server为了防止数据异常, 会报错而终止你的操作.
当然, 在SQL 2005/2008里, 在做[分离/删除]数据库时提供了一个选项[关闭所以连接]供勾选(SQL 2000好像没有哦), 然而[备份/还原]操作却没有此选择, 也许你会说可以先[脱机数据库]再做[备份还原]操作, 对, 但你会发现[脱机]处理太慢了J, 那在SQL2005以及SQL 2008下有哪些方法可以解决此问题呢???
解决办法:
存储过程代码如下所示:
--关闭用户打开的进程处理 USE master go IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[p_killspid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[p_killspid] go create proc p_killspid @dbname varchar(200) --要关闭进程的数据库名 as declare @programName nvarchar(200), @spid nvarchar(20) declare cDblogin cursor for select cast(spid as varchar(20)) AS spid from master..sysprocesses where dbid=db_id(@dbname) open cDblogin fetch next from cDblogin into @spid while @@fetch_status=0 begin --防止自己终止自己的进程 --否则会报错不能用KILL 来终止您自己的进程。 IF @spid <> @@SPID exec( 'kill '+@spid) fetch next from cDblogin into @spid end close cDblogin deallocate cDblogin go --用法 exec p_killspid 'fdoam'