SQL語句實現查詢SQL Server伺服器名稱和IP地址_MsSql

來源:互聯網
上載者:User

擷取伺服器名稱:

SELECT SERVERPROPERTY('MachineName')select @@SERVERNAMEselect 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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.