2013-10-02 39 views
1

我有一個包含多列的表,並且我想從這些值中消除空格值('')。查詢是:按列名稱更新循環中的值

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

,自表中包含大約55列,以便可能是一個循環將是一個可行的想法,而不是寫update語句爲每個列。

首先我檢查,如果循環工作:

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 

任何想法,我要走的軌道?

在此先感謝:-)

回答

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; 

/
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;