我是靠谱客的博主 顺心银耳汤,最近开发中收集的这篇文章主要介绍SQL语句实现查询SQL Server服务器名称和IP地址,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

获取服务器名称:

SELECT SERVERPROPERTY('MachineName')
select @@SERVERNAME
select HOST_NAME()

获取IP地址可以使用xp_cmdshell执行ipconfig命令:

--开启xp_cmdshell 
exec sp_configure'show advanced options', 1 
reconfigure with override 
exec sp_configure'xp_cmdshell', 1 
reconfigure with override 
exec sp_configure'show advanced options', 0 
reconfigure with override 
go 
 
begin 
declare @ipline varchar(200) 
declare @pos int 
declare @ip varchar(40) 
set nocount on 
set @ip = null 
  if object_id('tempdb..#temp') is not null drop table #temp 
  create table #temp(ipline varchar(200)) 
  insert #temp exec master..xp_cmdshell'ipconfig' 
  select @ipline = ipline 
  from #temp 
  where upper(ipline) like '%IPv4 地址%'--这里需要注意一下,系统不同这里的匹配值就不同 
  if @ipline is not null 
  begin 
    set @pos = charindex(':',@ipline,1); 
    set @ip = rtrim(ltrim(substring(@ipline , 
    @pos + 1 , 
    len(@ipline) - @pos))) 
  end 
  select distinct(rtrim(ltrim(substring(@ipline , 
  @pos + 1 , 
  len(@ipline) - @pos)))) as ipaddress from #temp 
drop table #temp 
 
 
set nocount off 
end 
go 

但是很多情况下由于安全问题是不允许使用xp_cmdshell,可以通过查询SYS.DM_EXEC_CONNECTIONS :

SELECT SERVERNAME = CONVERT(NVARCHAR(128),SERVERPROPERTY('SERVERNAME')) 
,LOCAL_NET_ADDRESS AS 'IPAddressOfSQLServer'
,CLIENT_NET_ADDRESS AS 'ClientIPAddress'
 FROM SYS.DM_EXEC_CONNECTIONS WHERE SESSION_ID = @@SPID

 

最后

以上就是顺心银耳汤为你收集整理的SQL语句实现查询SQL Server服务器名称和IP地址的全部内容,希望文章能够帮你解决SQL语句实现查询SQL Server服务器名称和IP地址所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(145)

评论列表共有 0 条评论

立即
投稿
返回
顶部