I have a multiple fields that needs to be put into a string only when there is something in the field and on top of that I don’t want the commas between fields if they are null. I tried using case when but am clearly doing something wrong and would appreciate some help with the following:
USE newCityCollection
UPDATE PropertyInformationDump
SET RegistryAdd = (CASE
WHEN b.OCAREOF IS NULL THEN Isnull(b.OCAREOF, '')
ELSE b.OCAREOF + ' ,'
END) + (CASE
WHEN b.O1STADD IS NULL THEN Isnull(b.O1STADD, '')
ELSE b.O1STADD + ' ,'
END) + (CASE
WHEN b.O2NDADD IS NULL THEN Isnull(b.O2NDADD, '')
ELSE b.O2NDADD + ' ,'
END) + (CASE
WHEN b.OSTNAME IS NULL THEN Isnull(b.OSTNAME, '')
ELSE b.OSTNAME + ' ,'
END) + (CASE
WHEN b.OCITYST IS NULL THEN Isnull(b.OCITYST, '')
ELSE b.OCITYST + ' ,'
END) + (CASE
WHEN b.OZIP IS NULL THEN Isnull(b.OZIP, '')
ELSE b.OZIP + ' ,'
END)
FROM dbo.vw_BRT b
WHERE BRTNumber = b.PARCEL
When I execute that on a field I get nada and am not sure why which is likely a fundemental misunderstanding of how CASE works. I did make sure those fields were actually null and not empty so that is not the problem.
Consider the following: when you join strings together in SQL, and one of them is
null, the result isnull(*). So, if you add the comma before eliminatingnulls, it’s a tad easier:No
CASEneeded here.COALESCEis similar toISNULLand would usually be recommended except for a few odd situations – for one, it’s part of standard SQL (useful if you ever have to work against other RDBMSes), for another it can accept multiple arguments and returns the first non-NULLone. For a third, it uses the most appropriate data type for the result considering the types of each expression –ISNULLalways tries to convert the second argument to the type of the first)(I’m also not sure what you we’re doing in your
CASEexpressions – you’d already established that, e.g.OCAREOFwas null – there was no need to then use anISNULLexpression to obtain'')(*) As Conrad points out, on SQL Server this does depend on
CONCAT_NULL_YIELDS_NULLbeingON, but it is by default and it really should be: