SQL - 如何确定主机名是否与已知别名匹配

时间:2015-04-13 22:33:16

标签: sql-server

下面是我创建的脚本,用于确定执行此代码的计算机是否与已知的服务器别名匹配。但是,我需要找到一种方法将此代码转换为函数。有没有一种更标准的方法可以在不诉诸CLR的情况下做到这一点? 我的理由是我有一台开发机器和一台生产机器。如果我在开发机器上运行一些代码,我想做一件事;如果我从生产服务器运行它,我想要发生其他事情。

DECLARE @cmd nvarchar(2000)
DECLARE @runtimeHost nvarchar(128)
DECLARE @devServerAlias nvarchar(128)
DECLARE @results table ( [output] bit )

SET @runtimeHost = HOST_NAME()  -- this would resolve to the non-FQDN machine name
SET @devServerAlias = 'serveralias' -- a known non-FQDN alias for what we think is the same machine as @runtimeHost

--original PowerShell script:
--PowerShell.exe -noprofile -executionpolicy bypass -command "& {foreach ($a in ([Net.DNS]::GetHostEntry(\"hostname.domain.com\")).addresslist.ipaddresstostring) { if ($a –eq [Net.DNS]::GetHostEntry(\"aliasname.domain.com\").addresslist.ipaddresstostring) { $true } else { $false } }}"
--The PowerShell resolves the IP address(es) and compares to find a match
SET @cmd = 'xp_cmdshell ''PowerShell.exe -noprofile -executionpolicy bypass -command "& {foreach ($a in ([Net.DNS]::GetHostEntry(\"' 
    + @runtimeHost 
    + '.domain.com\")).addresslist.ipaddresstostring) { if($a –eq [Net.DNS]::GetHostEntry(\"' 
    + @devServerAlias 
    + '.domain.com\").addresslist.ipaddresstostring) { $true } else { $false } }}"'''

-- Execute the Powershell.  The result comes as two lines, the first being the answer and the second being a NULL entry.
-- Because of this, we will need to store the result in a table
INSERT INTO @results ( [output] )
EXEC sp_executesql @cmd

SELECT TOP 1 [output] from @results

0 个答案:

没有答案