Get Hostname from FQDN

When working with a view or table, there may a need to extract the hostname from a fully qualified domain name (FQDN) column value. Below is a case statement that can be used to obtain the hostname.

The CHARINDEX(‘.’, FQDN) > 0 expression returns the position of the first period. If not found, it will return zero. When the expression is greater than zero, it will return the substring before the first period. If the original expression did not find a period, then the original column value in FQDN will be returned.

Here is a generic SQL query statement that can be used to help get hostnames from FQDNs. Simply replace FQDN with the actual column name containing the FQDN values and replace table with the actual table or view name.

select CASE When CHARINDEX('.', FQDN) > 0 THEN SUBSTRING(FQDN, 1, CHARINDEX('.',FQDN)-1) Else FQDN
END as 'HostName', FQDN from Table

gethostname