Here's what I would do:
with CatTitles as
(
--replace empty string with NULL
select case when LEN(CatTitle_E) = 0 then null else CatTitle_E end CatTitle_E
, case when LEN(CatTitle_F) = 0 then null else CatTitle_F end CatTitle_F
, case when LEN(CatTitle_G) = 0 then null else CatTitle_G end CatTitle_G
, case when LEN(CatTitle_J) = 0 then null else CatTitle_J end CatTitle_J
from #test1
)
select *
, COALESCE(CatTitle_F, CatTitle_G, CatTitle_J, CatTitle_E) Result
from CatTitles
Through that Common Table Expression I first take care of the null and empty string mess, then I use COALESCE to get the first non-null value. COALESCE will return the first non-null value in the parameter list, so if the order is not what you'd expected then you'll need to change it there.
**Edit:** based on the implementation of the UDF as posted by OP (the specs aren't 100% clear), here's a possible alternative:
with CatTitles as
(
--replace empty string with NULL
select case when LEN(CatTitle_E) = 0 then null else CatTitle_E end CatTitle_E
, case when LEN(CatTitle_F) = 0 then null else CatTitle_F end CatTitle_F
, case when LEN(CatTitle_G) = 0 then null else CatTitle_G end CatTitle_G
, case when LEN(CatTitle_J) = 0 then null else CatTitle_J end CatTitle_J
from #test1
)
select *
, COALESCE(CatTitle_F, CatTitle_E) CatTitle_F2
, COALESCE(CatTitle_G, CatTitle_E) CatTitle_G2
, COALESCE(CatTitle_J, CatTitle_E) CatTitle_J2
from CatTitles
↧