简体   繁体   中英

Oracle 11g - parsing words of a column in a sql query

I'm trying to update a CITY field. This is for Canada addresses, but I'm going to keep it simple for my issue. CITY fields contain only one word where the STATE field contains multiple words (usually no more than 3 words separated by a space.), but the majority of the STATE values contain two words separated by a space.

Example: CITY will show NEW and STATE will show YORK NY

Now I am trying to update CITY with it to show NEW YORK right now. Have not gotten to the part where I need to update the STATE as well. Baby steps I guess.

What I have:

UPDATE TABLE
SET CITY = CITY || ' ' || SUBSTR(STATE, 1, INSTR(STATE, ' '))
WHERE SUBSTR(STATE, 1, INSTR(STATE, ' ')) IS NOT NULL;


When I just run :

SELECT CITY || ' ' || SUBSTR(STATE, 1, INSTR(STATE, ' '))
WHERE SUBSTR(STATE, 1, INSTR(STATE, ' ')) IS NOT NULL; 


I get the first word of the STATE field, so it shows me I'm kind of on track.

Any info on this would be appreciated.

Thanks.

If you are trying to correct the data (though I and not 100% - if that is the case) then your code seems fine.

create table t1 (city varchar2(100), state varchar2(100)) insert into t1 values ('NEW','YORK NY')

update t1 set city = city ||' '||SUBSTR(STATE, 1, INSTR(STATE, ' ')) WHERE SUBSTR(STATE, 1, INSTR(STATE, ' ')) IS NOT NULL;

Now city column : New York

select state ,SUBSTR(STATE, length(state) -1, INSTR(STATE, ' ')) from t1
WHERE SUBSTR(STATE, 1, INSTR(STATE, ' ')) IS NOT NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM