【问题标题】:updating values in a loop by column name按列名更新循环中的值
【发布时间】:2023-03-04 13:43:01
【问题描述】:

我有一个包含几列的表,我想从值中删除空格值 (' ')。查询是:

update table
set column_name = trim(both ' ' from column_name)
where column_name like '% '

并且由于该表包含大约 55 列,因此循环可能是一个可行的想法,而不是为每一列编写更新语句。

首先我检查了循环是否正常工作:

declare
    column_name varchar2(2048);
    cursor pointer is
         select column_name into column_name from user_tab_cols where table_name = 'TABLE_NAME';

begin 
    for x in pointer
    loop
        dbms_output.put_line(x.column_name);
    end loop;
end;

是的,它正在工作。我在 dbms_output 窗口中获取列名。

现在, 这是我正在尝试做的事情,但似乎不起作用:

declare
    column_var varchar2(2048);
    cursor pointer is
         select column_name into column_var from user_tab_cols where table_name = 'TABLE_NAME';

begin 
    for x in pointer
    loop
         update table_name
         set x.column_var = trim(both ' ' from x.column_var)
         where x.column_var like '% ';
         commit;
    end loop;
end;

不幸的是,这不起作用。这是我得到的错误:

ORA-06550: line 11, column 18:
PLS-00302: component 'COLUMN_VAR' must be declared.
ORA-06550: line 11, column 16:
PL/SQL: ORA-00904: "X"."COLUMN_VAR": invalid identifier
ORA-06550: line 9, column 10:
PL/SQL: SQL Statement ignored

知道我要去哪里偏离轨道吗?

提前致谢:-)

【问题讨论】:

    标签: oracle plsql oracle11g plsqldeveloper


    【解决方案1】:

    我认为您需要提供实际的列名,而不是语句中表示列名的字符串。立即执行对您有用吗?

    declare
        column_var varchar2(2048);
        cursor pointer is
             select column_name into column_var from user_tab_cols where table_name = 'TABLE_NAME';
    
    begin 
       for x in pointer
       loop
             execute immediate 
                 'update table_name ' ||
                 'set '|| x.column_var ||' = trim(both '' '' from '|| x.column_var ||')'||
                 'where '|| x.column_var ||' like ''% ''';
             commit;
        end loop;
    end;
    

    【讨论】:

      【解决方案2】:

      你需要为此使用动态 sql

          BEGIN
            FOR t IN (select column_name from user_tab_cols where table_name = 'MyTable')
                         LOOP
           EXECUTE IMMEDIATE
               'update MyTable set '||t.column_name||' = trim(both '' '' from '||t.column_name||') where '||t.column_name||' like ''% ''';
      
            END LOOP;
      
          END;
      
      /
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-08
        • 1970-01-01
        • 2020-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多