2015-07-22 23 views
0

我有一個表,它的內容:如何找到爲例外的原因列在Oracle

ID A  B 
--- --- ---- 
1 123  &%df 
2 587  364 

的函數寫爲無效號碼(以下腳本)

CREATE OR REPLACE FUNCTION is_number RETURN number IS 
    A_var  number(15); 
    B_var  number(15); 
    BEGIN 

    for u in (select id, 
        A, 
        B, 
       from TABLE_NAME) LOOP 
    BEGIN 
     select 
      to_number(u.A), 
      to_number(u.B), 
      into A_var , B_var 
     from dual; 
    EXCEPTION 
     WHEN others THEN 
     update TABLE_NAME set ?????? = null where id = u.id; 
    END; 
    END LOOP; 

    return -1; 
END is_number; 

頂部腳本我要將??????替換爲列名作爲無效數字,在此示例中列名稱爲B
後面的腳本,表格內容爲:

ID A  B 
--- --- ---- 
1 123  
2 587  364 

回答

0

如果數字轉換錯誤將出現在兩列中,該怎麼辦?

試試這個:

create or replace function is_number return number is 
    a_var number(15); 
    b_var number(15); 
    function custom_to_number(v varchar2) return number is 
     result number; 
    begin 
     result:=to_number(v); 
     return result; 
     exception when others then 
      if(sqlcode = -6502) then 
       return null; 
      end if; 
      raise; 
    end; 
begin 
    for u in (select id 
        ,a 
        ,b 
       from table_name) 
    loop 
     a_var:=custom_to_number(u.a); 
     b_var:=custom_to_number(u.b); 
     if((u.a is not null and a_var is null) or (u.b is not null and b_var is null)) then 
      update table_name 
      set a = case when a_var is null then null else a end 
       ,b = case when b_var is null then null else b end 
      where id = u.id; 
     end if; 
    end loop; 
    return -1; 
end is_number; 
+0

這是簡單salution但是如果你有100列,對於任何的必須申報嘗試捕捉那麼代碼將是大 –

+0

我要爲列無效數據設置爲空值
不需要切換的情況下 –

+0

轉換,出現異常處理只在嵌套函數'custom_to_number'中實現一次。 – ksa

0

如果你的打算是,以取代它包含alphanuneric數據爲NULL表中的列,那麼你可以使用觸發器來達致這。

CREATE OR REPLACE TRIGGER trigger_Name BEFORE INSERT OR UPDATE OF 
A_var, B_var ON TABLE_NAME 
FOR EACH ROW 
    BEGIN 

     IF NOT((regexp_like (:NEW.A_var,'^[[:digit:]]+$'))) THEN 
     :NEW.A_var := NULL; 
     END IF; 

     IF NOT((regexp_like (:NEW.B_var,'^[[:digit:]]+$'))) THEN 
     :NEW.B_var := NULL; 
     END IF; 

    INSERT INTO TABLE_NAME(A_var, B_var) Values(:NEW.A_var, :NEW.B_var); 

END; 
相關問題