Вы можете попробовать это:
SELECT
IIF(B.MOBILECODE = DialingPhoneCode, RIGHT(B.MOBILE, LEN(B.MOBILE)-B.CODELENGTH), B.MOBILE) AS UPDATEDMOBILE,
IIF(B.FAXCODE = DialingPhoneCode, RIGHT(B.FAX, LEN(B.FAX)-B.CODELENGTH), B.FAX) AS UPDATEDFAX,
IIF(B.LANDLINECODE = DialingPhoneCode, RIGHT(B.LANDLINE, LEN(B.LANDLINE)-B.CODELENGTH), B.LANDLINE) AS UPDATEDLANDLINE,
B.COUNTRYCODE
FROM (
SELECT A.MOBILE, A.FAX, A.LANDLINE, A.COUNTRYCODE, A.DialingPhoneCode,A.CODELENGTH
,LEFT(A.MOBILE, A.CODELENGTH) AS MOBILECODE
,LEFT(A.Fax, A.CODELENGTH) AS FAXCODE
,LEFT(A.Landline, A.CODELENGTH) AS LANDLINECODE
FROM (
SELECT P1.Mobile,P1.Fax,P1.Landline,P1.CountryCode, P2.DialingPhoneCode
, LEN(P2.DialingPhoneCode) AS CODELENGTH
FROM PhoneNumbers P1
LEFT JOIN PhoneCodes P2
ON P1.CountryCode = P2.CountryCode)A )B
Функция IIF может использоваться только в SQL Server 2012 или более поздней версии.
Если вы используете более старую версию, вы можете использоватьоператор case для их замены.
Результат теста (я добавил еще два образца теста):
DB <> Fiddle
---- Обновление ----
Добавить Обновление и регистр операторов:
UPDATE PhoneNumbers
SET Mobile = C.UPDATEDMOBILE,
Fax = C.UPDATEDFAX,
Landline = C.UPDATEDLANDLINE
FROM
(
SELECT
CASE WHEN B.Mobile IS NULL THEN NULL
WHEN B.MOBILE IS NOT NULL AND B.MOBILECODE = DialingPhoneCode THEN RIGHT(B.MOBILE, LEN(B.MOBILE)-B.CODELENGTH)
ELSE B.MOBILE END AS UPDATEDMOBILE,
CASE WHEN B.Fax IS NULL THEN NULL
WHEN B.FAXCODE = DialingPhoneCode THEN RIGHT(B.FAX, LEN(B.FAX)-B.CODELENGTH)
ELSE B.FAX END AS UPDATEDFAX,
CASE WHEN B.Landline IS NULL THEN NULL
WHEN B.LANDLINECODE = DialingPhoneCode THEN RIGHT(B.LANDLINE, LEN(B.LANDLINE)-B.CODELENGTH)
ELSE B.LANDLINE END AS UPDATEDLANDLINE,
B.COUNTRYCODE, B.Mobile, B.Fax, B.Landline
FROM (
SELECT A.MOBILE, A.FAX, A.LANDLINE, A.COUNTRYCODE, A.DialingPhoneCode,A.CODELENGTH
,LEFT(A.MOBILE, A.CODELENGTH) AS MOBILECODE
,LEFT(A.Fax, A.CODELENGTH) AS FAXCODE
,LEFT(A.Landline, A.CODELENGTH) AS LANDLINECODE
FROM (
SELECT P1.Mobile,P1.Fax,P1.Landline,P1.CountryCode, P2.DialingPhoneCode
, LEN(P2.DialingPhoneCode) AS CODELENGTH
FROM PhoneNumbers P1
LEFT JOIN PhoneCodes P2
ON P1.CountryCode = P2.CountryCode)A )B )C
WHERE C.Mobile = PhoneNumbers.Mobile
AND C.Fax = PhoneNumbers.Fax
AND C.Landline = PhoneNumbers.Landline
Результат теста:
DB <>Fiddle