微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQL语句实现查询SQL Server服务器名称和IP地址

获取服务器名称

rush:sql;"> SELECT SERVERPROPERTY('MachineName') select @@SERVERNAME select HOST_NAME()

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

rush:sql;"> --开启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,len(@ipline) - @pos)))) as ipaddress from #temp
drop table #temp

set nocount off
end
go

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

rush:sql;"> 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

原文地址:https://www.jb51.cc/mssql/63089.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐