1

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

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

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

提前致谢 :-)

4

2 回答 2

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;
于 2013-10-02T07:42:17.803 回答
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;

/
于 2013-10-02T08:02:15.540 回答