码农的笔记

Delphi虽好,但已不流行; 博客真好,可以做笔记

博客园 首页 新随笔 联系 订阅 管理

来源:http://www.itpub.net/thread-193247-1-1.html

先保存,以后研究一下

 

 

 

 1 *--获取连接SQL服务器的信息  
 2 
 3            所有连接本机的:操作的数据库名,计算机名,用户名,网卡物理地址,IP地址,程序名  
 4 -*/  
 5 
 6 /*--调用示例  
 7            --显示所有本机的连接信息  
 8            exec  p_getlinkinfo  
 9 
10            --显示所有本机的连接信息,包含ip地址  
11            exec  p_getlinkinfo  @includeip=1  
12 
13            --显示连接指定数据库的信息  
14            exec  p_getlinkinfo  '客户资料'  
15 --*/  
16 if  exists  (select  *  from  dbo.sysobjects  where  id  =  object_id(N'[dbo].[p_getlinkinfo]')  and  OBJECTPROPERTY(id,  N'IsProcedure')  =  1)  
17 drop  procedure  [dbo].[p_getlinkinfo]  
18 GO  
19 
20 create  proc  p_getlinkinfo  
21 @dbname  sysname=null,                        --要查询的数据库名,默认查询所有数据库的连接信息  
22 @includeip  bit=0                                    --是否显示IP地址,因为查询IP地址比较费时,所以增加此控制  
23 as  
24 declare  @dbid  int  
25 set  @dbid=db_id(@dbname)  
26 
27 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))  
28 insert  into  #tb(hostname,dbname,net_address,loginname,prog_name)  
29 select  distinct  hostname,db_name(dbid),net_address,loginame,program_name  from  master..sysprocesses  
30            where  hostname<>''  and  (@dbid  is  null  or  dbid=@dbid)  
31 
32 if  @includeip=0  goto  lb_show    --如果不显示IP地址,就直接显示  
33 
34 declare  @sql  varchar(500),@hostname  nchar(128),@id  int  
35 create  table  #ip(hostname  nchar(128),a  varchar(200))  
36 declare  tb  cursor  local  for  select  distinct  hostname  from  #tb  
37 open  tb  
38 fetch  next  from  tb  into  @hostname  
39 while  @@fetch_status=0  
40 begin  
41            set  @sql='ping  '+@hostname+'  -a  -n  1  -l  1'  
42            insert  #ip(a)  exec  master..xp_cmdshell  @sql  
43            update  #ip  set  hostname=@hostname  where  hostname  is  null  
44            fetch  next  from  tb  into  @hostname  
45 end  
46 
47 update  #tb  set  net_ip=left(a,patindex('%:%',a)-1)  
48 from  #tb  a  inner  join  (  
49 select  hostname,a=substring(a,patindex('Ping  statistics  for  %:%',a)+20,20)  from  #ip  
50            where  a  like  'Ping  statistics  for  %:%')  b  on  a.hostname=b.hostname  
51 
52 lb_show:  
53 select  id,数据库名=dbname,客户机名=hostname,用户名=loginname  
54            ,网卡物理地址=net_address,IP地址=net_ip,应用程序名称=prog_name  from  #tb  
55 
56 go

 

posted on 2022-04-30 09:43  码农的笔记  阅读(1055)  评论(0编辑  收藏  举报