查詢所有SQL使用者的連線資訊(可顯示IP)
阿新 • • 發佈:2019-01-01
ifobject_id('p_getlinkinfo','P')isnotnulldropproc p_getlinkinfo
gocreateproc p_getlinkinfo
@dbname sysname=null, --要查詢的資料庫名,預設表示所有 @includeipbit=0--是否顯示IP資訊 asbegindeclare@dbidintset@dbid=db_id(@dbname)
ifobject_id('tempdb..#tb')isnotnulldroptable #tb
ifobject_id('tempdb..#ip')isnotnulldroptable
createtable #tb
(id intidentity(1,1),
dbname sysname,
hostname nchar(128),
loginname nchar(128),
net_address nchar(12),
net_ip nvarchar(15),
prog_name nchar(128))
insertinto #tb(hostname,dbname,net_address,loginname,prog_name)
db_name(dbid),
net_address,
loginame,
program_name
from master..sysprocesses
where hostname!=''and(@dbidisnullor dbid=@dbid)
if@includeip=0goto lb_show --不顯示IP declare@sqlvarchar(500),@hostnamenchar(128),@idintcreatetable #ip(hostname
declare tb cursor local forselectdistinct hostname from #tb
open tb
fetchnextfrom tb into@hostnamewhile@@fetch_status=0beginset@sql='ping '+@hostname+' -a -n 1 -l 1'insert #ip(a) exec master..xp_cmdshell @sqlupdate #ip set hostname=@hostnamewhere hostname isnullfetchnextfrom tb into@hostnameendupdate #tb set net_ip=left(a,patindex('%:%',a)-1)
from #tb a innerjoin
(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
endgoexec p_getlinkinfo @dbname='DB_WIP',@includeip=1