2013-10-20 35 views
0

我找到了下面的解決方案,但我需要使用PL/SQL存儲過程完成此操作。將可空列轉換爲現有表中不可爲空的可重新運行的腳本

declare 
    l_nullable varchar2(1); 
begin 
    select nullable into l_nullable 
    from user_tab_columns 
    where table_name = 'PV_REPORT_DETAILS' 
    and column_name = 'FEED_ID'; 

    if l_nullable = 'Y' then 
    execute immediate 'alter table PV_REPORT_DETAILS modify (Feed_ID not null)'; 
    end if; 

    select nullable into l_nullable 
    from user_tab_columns 
    where table_name = 'PV_REPORT_DETAILS' 
    and column_name = 'CURRENT_RUN_ID'; 

    if l_nullable = 'Y' then 
    execute immediate 'alter table PV_REPORT_DETAILS modify (Current_Run_ID not null)'; 
    end if; 

    select nullable into l_nullable 
    from user_tab_columns 
    where table_name = 'PV_REPORT_DETAILS' 
    and column_name = 'PREVIOUS_RUN_ID'; 

    if l_nullable = 'Y' then 
    execute immediate 'alter table PV_REPORT_DETAILS modify (Previous_Run_ID not null)'; 
    end if; 
end; 
+0

:?有什麼問題,你已經找到了匿名塊是正確的,唯一要做的就是包裝,這是procecure。而肯定的,這是再因爲下一次來自user_tab_columns視圖的可空列將獲取「N」 –

回答

1

我覺得作者想要一個過程,這將使所有空列NOT NULL列在一個給定的表。嘗試這種解決方案:

CREATE TABLE my_test_table (
    id NUMBER NOT NULL, 
    name VARCHAR2(20), 
    salary NUMBER 
); 

DESC my_test_table; 
Name Null  Type   
------ -------- ------------ 
ID  NOT NULL NUMBER  
NAME   VARCHAR2(20) 
SALARY   NUMBER
CREATE OR REPLACE PROCEDURE nullable_to_not_nullable(p_table_name IN VARCHAR2) 
AS 
    CURSOR c_list_nullable_columns IS 
    SELECT column_name 
     FROM user_tab_columns 
    WHERE table_name = UPPER(p_table_name) 
     AND nullable = 'Y'; 
BEGIN 
    FOR v_rec IN c_list_nullable_columns 
    LOOP 
    EXECUTE IMMEDIATE 'ALTER TABLE ' || p_table_name || ' MODIFY (' || v_rec.column_name || ' NOT NULL)'; 
    END LOOP; 
END nullable_to_not_nullable; 
/

BEGIN 
    nullable_to_not_nullable('my_test_table'); 
END; 
/

DESC my_test_table; 
Name Null  Type   
------ -------- ------------ 
ID  NOT NULL NUMBER  
NAME NOT NULL VARCHAR2(20) 
SALARY NOT NULL NUMBER
+0

如果你足夠瘋狂地命名帶有需要引號的特殊字符的表或列,那麼這將不起作用。 –