Ghat Workman 2015-02-20T13:50:42
Below are two sql statements, one to select, and see the impact of the update statement, and the update statement. Back up your tables before you run any updates and always test that the update is doing what you expect by running it as a select statement first. \n\nNote: I made the assumption that you want to keep the postcode in the format it was originally entered. eg if it was entered as xxxxx it will be saved as xxxxx and if it was entered as xx-xxx it will be saved as xx-xxx. \n\nCheck to see what the update statement will do: \n\nselect ID, STREET, TOWN, POSTCODE, COUNTRY, \ncase when substr(TOWN, 3, 1) = '-' like '%-%' then trim(substr(TOWN,7, length(TOWN)-6)) else trim(substr(TOWN,6, length(TOWN)-5)) end as NEW_TOWN,\ncase when substr(TOWN, 3, 1) = '-' like '%-%' then substr(TOWN, 1, 6) else substr(TOWN, 1, 5) end as NEW_POSTCODE--Assumes you want to keep the dash if it exists\nfrom ADDRESSES\nwhere COUNTRY like'%UK%' --contains string UK\nand trim(POSTCODE) is null -- postcode is empty\nand (\n length(trim(translate(substr(TOWN, 1, 5), '0123456789', ' '))) is null -- town starts with xxxxx digits\n or\n (length(trim(translate(substr(TOWN, 1, 2)||substr(TOWN,4,3, '0123456789', ' ')))) and substr(TOWN, 3, 1) = '-') -- town starts with xx-xxx digits\n )\n;\n\n\nIf you are satisfied, run the update statement. \n\nupdate ADDRESSES\nset\nTOWN = case when substr(TOWN, 3, 1) = '-' like '%-%' then trim(substr(TOWN,7, length(TOWN)-6)) else trim(substr(TOWN,6, length(TOWN)-5)) end,\nPOSTCODE = case when substr(TOWN, 3, 1) = '-' like '%-%' then substr(TOWN, 1, 6) else substr(TOWN, 1, 5) end --Assumes you want to keep the dash if it exists\nfrom ADDRESSES\nwhere COUNTRY like'%UK%' --contains string UK\nand trim(POSTCODE) is null -- postcode is empty\nand (\n length(trim(translate(substr(TOWN, 1, 5), '0123456789', ' '))) is null -- town starts with xxxxx digits\n or\n (length(trim(translate(substr(TOWN, 1, 2)||substr(TOWN,4,3, '0123456789', ' ')))) and substr(TOWN, 3, 1) = '-') -- town starts with xx-xxx digits\n )\n;\n\n\nI hope this will at least serve as a starting point. ",