【问题标题】:Update one column of each row in a table [PL/SQL, unix scripting]更新表中每一行的一列 [PL/SQL,unix 脚本]
【发布时间】:2021-12-18 09:31:44
【问题描述】:

我有一个 12 列的表:

表1:

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

我想在循环中使用第三列数据并从另一个表中获取“最佳匹配”数据。

表2:

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

将在循环中修剪第 3 列数据,直到获取 table2 中的匹配项。

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

【问题讨论】:

    标签: oracle for-loop plsql scripting sql-update


    【解决方案1】:

    您需要做的是创建一个过程,然后在该过程中声明cursorvariable_c_row cursor_name%ROWTYPE

    在程序中,这将是内容:

    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;
    

    由于该问题没有 DDL 或 DML,我最多只能提供一个广泛的答案,尚未经过测试。

    【讨论】:

    • 你能简单解释一下这些:variable_c_row.row3,l_yourrow,以及begin之后的select row4语句吗?将尝试在 shell 脚本中添加并运行它
    • @dcdum2018 声明一个变量,如variable_c_row cursor_name%ROWTYPE。此变量将创建一个数组,您可以使用变量和由“。”分隔的列访问该行中的任何列。更正 l_yourrow,意思是说 l_countryname(已编辑):在您的声明中使用 l_countryname table2.row4%type
    • 我认为 row4 在这里是 col4 -> select col4 from table2 into l_countryname where row1 = match; where match := variable_c_row.row3 你能简单解释一下这部分吗? (例如 row1 是什么?)谢谢
    • 正确。它应该是col4。我在没有测试的情况下编写了代码,似乎有点迷失了。它应该说 col3,而不是 row3。它会得到你的col3。我还更正了一些代码。
    • 谢谢!我能够测试它。只有微小的变化:match := ... length(match)-1)
    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2015-08-07
    • 1970-01-01
    相关资源
    最近更新 更多