This seems to work base on our small sample data. if you have example that break the code then please add them to the table variable code:declare @tA table (CompanyID varchar(200))declare @tB table (CompanyID varchar(200), CompanyName varchar(100))insert @tAselect 'AAA' union allselect 'AAA.BBB' union allselect 'AAA.BBB.CCC' union allselect 'AAA.BBB.CCC.DDD' union allselect 'AAA.BBB.CCC.DDD.EEE' union allselect 'AAA.BBB.CCC.DDD.EEE.FFF' insert @tBselect 'AAA', 'c_AAA' union allselect 'AAA.BBB.CCC', 'c_AAA.BBB.CCC' union allselect 'AAA.BBB.CCC.DDD', 'c_AAA.BBB.CCC.DDD'select companyName ,[tA_CompanyID] ,[tB_CompanyID]from ( select b.companyName ,a.companyid [tA_CompanyID] ,b.companyid [tB_CompanyID] ,rn = row_number() over (partition by a.companyid order by len(a.companyid) - len(b.companyid)) from @tB b join @tA a on charindex(reverse(b.companyid), reverse(a.companyid)) > 0 ) dwhere rn = 1output:companyName tA_CompanyID tB_CompanyID------------------------------------------------------------------------------------c_AAA AAA AAAc_AAA AAA.BBB AAAc_AAA.BBB.CCC AAA.BBB.CCC AAA.BBB.CCCc_AAA.BBB.CCC.DDD AAA.BBB.CCC.DDD AAA.BBB.CCC.DDDc_AAA.BBB.CCC.DDD AAA.BBB.CCC.DDD.EEE AAA.BBB.CCC.DDDc_AAA.BBB.CCC.DDD AAA.BBB.CCC.DDD.EEE.FFF AAA.BBB.CCC.DDD
Be One with the OptimizerTG