CoffeeStudent CoffeeStudent - 1 year ago 115
SQL Question

TSQL IF Operator results invalid column

My objective, is to select the first available address. If there isn't a AddressCity, then I should select the AddressRegion, and if there is not a AddressRegion I should select the AddressCountry.

IF AddressCity IS NOT NULL
SELECT AddressName + ' is from ' + AddressCity
ELSE
IF AddressRegion IS NOT NULL
SELECT Address+ ' is from ' + AddressRegion
ElSE
IF AddressCountry IS NOT NULL
SELECT AddressName + ' is from ' + AddressCountry
FROM DBO.Address


When I execute it, I get Invalid column name 'AddressCity'

Answer Source

You want something like case or coalesce():

SELECT coalesce(AddressName + ' is from ' + AddressCity,
                AddressName + ' is from ' + AddressRegion   
                AddressName + ' is from ' + AddressCountry
               )
FROM DBO.Address;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download