SQL语句实现查询SQL Server服务器名称和IP地址
获取服务器名称:
SELECTSERVERPROPERTY('MachineName') select@@SERVERNAME selectHOST_NAME()
获取IP地址可以使用xp_cmdshell执行ipconfig命令:
--开启xp_cmdshell execsp_configure'showadvancedoptions',1 reconfigurewithoverride execsp_configure'xp_cmdshell',1 reconfigurewithoverride execsp_configure'showadvancedoptions',0 reconfigurewithoverride go begin declare@iplinevarchar(200) declare@posint declare@ipvarchar(40) setnocounton set@ip=null ifobject_id('tempdb..#temp')isnotnulldroptable#temp createtable#temp(iplinevarchar(200)) insert#tempexecmaster..xp_cmdshell'ipconfig' select@ipline=ipline from#temp whereupper(ipline)like'%IPv4地址%'--这里需要注意一下,系统不同这里的匹配值就不同 if@iplineisnotnull begin set@pos=charindex(':',@ipline,1); set@ip=rtrim(ltrim(substring(@ipline, @pos+1, len(@ipline)-@pos))) end selectdistinct(rtrim(ltrim(substring(@ipline, @pos+1, len(@ipline)-@pos))))asipaddressfrom#temp droptable#temp setnocountoff end go
但是很多情况下由于安全问题是不允许使用xp_cmdshell,可以通过查询SYS.DM_EXEC_CONNECTIONS:
SELECTSERVERNAME=CONVERT(NVARCHAR(128),SERVERPROPERTY('SERVERNAME')) ,LOCAL_NET_ADDRESSAS'IPAddressOfSQLServer' ,CLIENT_NET_ADDRESSAS'ClientIPAddress' FROMSYS.DM_EXEC_CONNECTIONSWHERESESSION_ID=@@SPID