按列名更新循环中的值

时间:2013-10-02 07:24:52

标签: oracle plsql oracle11g plsqldeveloper

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

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

知道我要离开赛道吗?

提前致谢: - )

2 个答案:

答案 0 :(得分:3)

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

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;

答案 1 :(得分:1)

您需要为此

使用动态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;

/
相关问题