I am dealing with phone system and have to work with multiple service vendors. For one vendor I have a MySQL table country_codes
like this -
--
update cc set
country_code = t.country_code
from country_codes cc
join (
select country_code, country, char_length(trim(cast(country_code as char))) as code_len
from country_codes
where country_code <> 0
) t on
t.country_code = cast(substr(cast(cc.area_code as char), 1, t.code_len) as signed integer) and
cc.country_code = 0 and
cc.country like concat(t.country, '%')
I've added cc.country like concat(t.country, '%')
to condition to be more specific but it assumes that each cellular network name starts with its country name - so if it's not true omit it.
Added after @Sachyn comment:
Test code used on SQLZOO works fine, it is for testing only, it's not an update query:
select cc.*, t.country_code as new_country_code
from (
select 93 as country_code, 93 as area_code , 'Afghanistan' as country union
select 0 , 9375 , 'Afghanistan Cellular-AT' union
select 0 , 9370 , 'Afghanistan Cellular-AWCC' union
select 355, 355 , 'Albania' union
select 0 , 35568, 'Albania Cellular-AMC' union
select 0 , 35567, 'Albania Cellular-Eagle' union
select 213, 213 , 'Algeria' union
select 0 , 21377, 'Algeria Cellular-Djezzy' union
select 0 , 2135 , 'Algeria Cellular-Wataniya'
) cc
join (
select country_code, country, char_length(rtrim(cast(country_code as char))) as code_len
from (
select 93 as country_code, 93 as area_code , 'Afghanistan' as country union
select 0 , 9375 , 'Afghanistan Cellular-AT' union
select 0 , 9370 , 'Afghanistan Cellular-AWCC' union
select 355, 355 , 'Albania' union
select 0 , 35568, 'Albania Cellular-AMC' union
select 0 , 35567, 'Albania Cellular-Eagle' union
select 213, 213 , 'Algeria' union
select 0 , 21377, 'Algeria Cellular-Djezzy' union
select 0 , 2135 , 'Algeria Cellular-Wataniya'
) c
where country_code <> 0
) t on
t.country_code = cast(substr(cast(cc.area_code as char), 1, t.code_len) as signed integer) and
cc.country_code = 0 and
cc.country like concat(t.country, '%')