用T-SQL获得当前连接客户端IP和机器名用T-SQL获得当前连接客户端IP和机器名  Create proc usp_getClient_infor 
  as 
  set nocount on
  
  Declare @rc int
  Declare @RowCount int
  
  Select @rc=0
  Select @RowCount=0
  
  begin
  --//create temp table ,save sp_who information
   create table #tspid(
   spid int null,
   ecid int null,
   status nchar(60) null,
   loginname nchar(256) null,
   hostname nchar(256) null,
   blk bit null,
   dbname nchar(256) null,
   cmd nchar(32)
   )
  
  --//create temp table save all SQL client IP and hostname and login time
  Create table #userip(
   [id]int identity(1,1),
   txt varchar(1000),
  )
  
  --//Create result table to return recordset
  Create table #result(
   [id]int identity(1,1),
   ClientIP varchar(1000),
   hostname nchar(256),
   login_time datetime default(getdate())
  
   )
  --//get host name by exec sp_who ,insert #tspid from sp_who,
  insert into #tspid(spid,ecid,status,loginname,hostname,blk,dbname,cmd) exec sp_who 
  
  declare @cmdStr varchar(100), 
   @hostName nchar(256), 
   @userip varchar(20), 
   @sendstr varchar(100)
   
  
  --//declare a cursor from table #tspid
  declare tspid cursor 
  for select distinct hostname from #tspid with (nolock) where spid>50 
  for read only
  
  open tspid
    fetch next from tspid into @hostname
    While @@FETCH_STATUS = 0
    begin
   select @cmdStr='ping '+rtrim(@hostName)
   
   insert into #userip(txt) exec master..xp_cmdshell @cmdStr 
   
   select @rowcount=count(id) from #userIP
  
  
   if @RowCount=2 --//no IP feedback package
   begin
   insert into #Result(ClientIP,hostname) values('Can not get feedback package from Ping!',@hostname)
   end
   if @RowCount>2 
   begin
   select @userip=substring(txt,charindex('[',txt)+1,charindex(']',txt)-charindex('[',txt)-1) 
   from #userIP
   where txt like 'Pinging%'
   
   insert into #Result(ClientIP,hostname) values(@userIP,@hostname)
   end
   select @rc=@@error
   if @rc=0
   truncate table #userip --//clear #userIP table
  
    fetch next from tspid into @hostname
   end 
  
  close tspid
  deallocate tspid
  
  select * from #result with(nolock)
  
  drop table #tspid 
  drop table #userip
  drop table #result
  end
  go
  exec usp_getClient_infor

解决方案 »

  1.   

    Create Procedure GetIPasdeclare @ip varchar(20)declare @hst varchar(20)declare @sql varchar(100)declare @str varchar(100)set @str='PING '+Host_Name() -- 这里改为:set @str='PING '+Host_Name() + ' -n 1'create table #tmp(aa varchar(200))insert #tmp exec master..xp_cmdshell @strselect top 1 @ip = replace(left(aa,charindex(':',aa)-1),'Reply from ','') from #tmp where aa like 'reply from %:%'drop table #tmpselect @ip
      

  2.   

    我是想获得服务器的IP地址,不是客户机的IP地址,比如说服务器是192.168.1.2和192.168.1.3,客户机是192.168.100和192.168.1.101,我是想知道客户机100在使用存储过程A的时候是连接的哪个服务器,因为我在1.2服务器上做了跨服务器查询,有部分查询是转到1.3上执行的,有没有办法可以得到当前客户机是连接到哪台服务器的?