Home > Enterprise >  Update one column of each row in a table [PL/SQL, unix scripting]
Update one column of each row in a table [PL/SQL, unix scripting]

Time:11-05

i have a table with 12 columns:

table1:

1 2 3 4 5 6 7 8 9 10 11 12
abc 1 000 aaa zzz 2 234 OOO 00001 01 123 214
def 2 023 bbb yyy 4 345 PPP 00002 02 133 224
ghi 3 011 ccc xxx 6 456 QQQ 00003 03 143 234
jkl 4 112 ddd www 8 567 RRR 00004 04 153 244

i would like to use 3rd column data in a loop and fetch 'best match' data from another table.

table2:

1 2 3 4
0 777 676 america
00 888 878 england
01 999 989 france
02 666 656 germany

3rd column data will be trimmed in the loop until a match in table2 is fetched.

first row:
iter 1: table1 row1 col3=000 -- no match in table
iter 2: table1 row1 col3=00 -- return england, replace table1 row1 col12=214 with 'england'

updated row: abc,1,000,aaa,zzz,2,234,OOO,00001,01,123,england


second row:
iter 1: table1 row2 col3=023 -- no match in table
iter 2: table1 row2 col3=02 -- return germany, replace table1 row1 col12=224 with 'germany'

updated row: def,2,023,bbb,yyy,4,345,PPP,00002,02,133,germany

CodePudding user response:

What you will need to do is create a procedure, then within the procedure declare a cursor as well as a variable_c_row cursor_name%ROWTYPE.

Within the procedure, this will be the contents:

OPEN cursor_name

FETCH cursor_name INTO variable_c_row;

WHILE cursor_name%FOUND LOOP
    -- Declare a number variable (i)
    i := 0;
    -- Declare a varchar variable (match)
    match := variable_c_row.col3
    
    WHILE length(match) > 0 LOOP OR l_countryname IS NULL
      begin
        -- Declare a yourrow%ROWTYPE variable (l_countryname)
        SELECT col4 FROM table2 INTO l_countryname WHERE col1 = match;
        
        UPDATE table1 SET col12 = l_countryname;
      exception when no_data_found then null;
      end;

      i := i 1;
      match := substr(variable_c_row.cow3, 0, length(match)-i);
    END LOOP;
  FETCH cursor_name INTO variable_c_row;
END LOOP;

CLOSE cursor_name;

Since the question had no DDL or DML, the most I can provide is a broad answer, which has not been tested.

  • Related