--
擷取SQL Server伺服器的串連資訊用指令碼(在原鄒建寫的基礎上作一點改進)
declare
@dbname sysname,
--要查詢的資料庫名(為空白為所有),預設查詢所有資料庫的串連資訊
@includeip bit
--是否顯示IP地址(0否,1是),因為查詢IP地址比較費時,所以增加此控制
select @dbname=null,@includeip=1
declare @dbid int
set @dbid=db_id(@dbname)
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
drop table #ip
lb_show:
select id,資料庫名=dbname,客戶機名=hostname,使用者名稱=loginname
,網卡物理地址=net_address,IP地址=net_ip,應用程式名稱=prog_name
from #tb
drop table #tb
--查詢結果:
------------------------------------------------------------------------------------------------------------
----一段查詢SQL Server伺服器阻塞和死結資訊用的指令碼
declare @spid int,@bl int,
@intTransactionCountOnEntry int,
@intRowcount int,
@intCountProperties int,
@intCounter int
create table #tmp_lock_who (
id int identity(1,1),
spid smallint,
bl smallint)
insert into #tmp_lock_who(spid,bl) select 0 ,blocked
from (select * from sysprocesses where blocked>0 ) a
where not exists(select * from (select * from sysprocesses where blocked>0 ) b
where a.blocked=spid)
union select spid,blocked from sysprocesses where blocked>0
-- 找到暫存資料表的記錄數
select @intCountProperties = Count(*),@intCounter = 1
from #tmp_lock_who
if @intCountProperties=0
select N'現在沒有阻塞和死結資訊' as message
-- 迴圈開始
while @intCounter <= @intCountProperties
begin
-- 取第一條記錄
select @spid = spid,@bl = bl
from #tmp_lock_who where Id = @intCounter
begin
if @spid =0
select N'引起資料庫死結的是: '+ CAST(@bl AS VARCHAR(10)) + N'進程號,其執行的SQL文法如下'
else
select N'進程號SPID:'+ CAST(@spid AS VARCHAR(10))+ N'被' + N'進程號SPID:'+ CAST(@bl AS VARCHAR(10)) +N'阻塞,其當前進程執行的SQL文法如下'
DBCC INPUTBUFFER (@bl )
end
-- 迴圈指標下移
set @intCounter = @intCounter + 1
end
drop table #tmp_lock_who
附:殺死相關會話的指令碼為 kill SPID 注意SPID為常量,不能為變數,要用變數,請用動態語句