• SQL Server获取连接的IP地址


    来源: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
  • 相关阅读:
    课后作业07--二分法查找算法代码
    检索03 -- 二分法查找
    课堂随笔05--冒泡排序
    课后作业 06 -- 小数后几位精确判断并输出
    课后作业 05 -- 输出一段带字母与数字的随机数
    课后作业 04 --DateTime应用,判断多久后生日之类
    检索02--随机数种子的一些概念和理解
    课堂随笔04--关于string类的一些基本操作
    P1174 互素
    P1001 第K极值
  • 原文地址:https://www.cnblogs.com/dmqhjp/p/16209486.html
Copyright © 2020-2023  润新知