I need to compare the Nodes column SysName with Nodes column DNSname to determine any nodes which have DNS entries (hostnames) that do not match their SysName. I've created this SQL query to compare the two Nodes columns using the SUBSTRING function to strip only the hostname part from the stored FQDN string. The SysName and DNS columns are stored as FQDN strings. The SQL query executes okay as coded below with given WHERE clause (not the result I'm looking for) but it will throw 'Invalid column name 'SysName_hostname' error when using Alias name with the WHERE clause (WHERE SysName_hostname <> DNS_hostname). I understand why this is. Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. I've tried using the SUBSTRING functions for the conditional in the WHERE clause (WHERE SUBSTRING(Nodes.SysName, 1, CHARINDEX('.', Nodes.SysName) - 1) <> SUBSTRING(Nodes.DNS, 1, CHARINDEX('.', Nodes.DNS) - 1)
but this throws the error 'Invalid length parameter in SUBSTRING function'. Also, if I change WHERE clause to (WHERE Nodes.SysName <> Nodes.DNS) it also throws an 'Invalid length parameter in SUBSTRING function' (again, not the result I'm looking for). I don't understand why SUBSTRING is throwing a length error in the WHERE clause but works fine when used in column selection.
Any advice how to get this SQL query to work to be able to compare the two aliased columns?
SELECT TOP 10
Nodes.Caption
, Nodes.SysName
, Nodes.DNS
, SUBSTRING(Nodes.SysName, 1, CHARINDEX('.', Nodes.SysName) - 1) AS SysName_hostname
, SUBSTRING(Nodes.DNS, 1, CHARINDEX('.', Nodes.DNS) - 1) AS DNS_hostname
FROM Nodes
WHERE Nodes.Caption <> Nodes.SysName