可重新运行的脚本,用于将可空列转换为现有表中不可为空的列

时间:2013-10-20 19:30:37

标签: sql oracle

我找到了下面的解决方案,但我需要使用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;

2 个答案:

答案 0 :(得分:1)

看一下Oracle的CREATE PROCEDURE语法。它应该是你正在寻找的。

http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_6009.htm#i2072424

CREATE [OR REPLACE] PROCEDURE procedure_name
    [ (parameter [,parameter]) ]

IS
    [declaration_section]

BEGIN
    executable_section

[EXCEPTION
    exception_section]

END [procedure_name];

答案 1 :(得分:1)

我认为作者想要一个过程,它会使给定表中的所有可为空的列都不是空列。试试这个解决方案:

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