选择返回时没有oracle select into变量?

时间:2012-01-26 13:45:58

标签: oracle exception select

declare
 fName varchar2(255 char);
begin
 SELECT x.constraint_name into fName FROM all_constraints x
 JOIN all_cons_columns c ON
 c.table_name = x.table_name AND c.constraint_name = x.constraint_name
 WHERE x.table_name = 'MY_TABLE_NAME' AND x.constraint_type = 'R' AND c.column_name ='MY_COLUMN_NAME';
 if fName is not null THEN
  execute immediate 'alter table MY_TABLE_NAME drop constraint ' || fName;
 end if;

 SELECT x.constraint_name into fName FROM all_constraints x
 JOIN all_cons_columns c ON
 c.table_name = x.table_name AND c.constraint_name = x.constraint_name
 WHERE x.table_name = 'OTHER_MY_TABLE_NAME' AND x.constraint_type = 'R' AND c.column_name ='OTHER_MY_COLUMN_NAME';
 if fName is not null THEN
  execute immediate 'alter table OTHER_MY_TABLE_NAME drop constraint ' || fName;
 end if;
end;

嗨@, 我正在使用上面的代码来获取我想要删除的约束的名称,并且我有很多这样的select into而不是if - >删除声明。 我的问题是,如果其中一个选择没有返回任何异常,则抛出异常。我可以捕获异常,但是在“begin end”结构的末尾(所以在所有select语句之后,所以其余的drop永远不会被执行)。如何安排这个,如果选择返回什么,我只是不想放弃任何东西:)

如果有另一种方法来定义一个变量并从select中填充它而不抛出异常,无论返回的名称是否为null,我都会更喜欢它:)(现在我只是让这个选择工作,除了选择不返回的情况:))

2 个答案:

答案 0 :(得分:6)

使用多个开始/异常/结束块:

declare
 fName varchar2(255 char);
begin
 begin
   SELECT x.constraint_name into fName FROM all_constraints x
   JOIN all_cons_columns c ON
   c.table_name = x.table_name AND c.constraint_name = x.constraint_name
   WHERE x.table_name = 'MY_TABLE_NAME' AND x.constraint_type = 'R' AND c.column_name ='MY_COLUMN_NAME';
exception
  when no_data_found then
    fName := null;
end;

 if fName is not null THEN
  execute immediate 'alter table MY_TABLE_NAME drop constraint ' || fName;
 end if;

begin    
 SELECT x.constraint_name into fName FROM all_constraints x
 JOIN all_cons_columns c ON
 c.table_name = x.table_name AND c.constraint_name = x.constraint_name
 WHERE x.table_name = 'OTHER_MY_TABLE_NAME' AND x.constraint_type = 'R' AND c.column_name ='OTHER_MY_COLUMN_NAME';
exception
  when no_data_found then
    fName := null;
end;

 if fName is not null THEN
  execute immediate 'alter table OTHER_MY_TABLE_NAME drop constraint ' || fName;
 end if;
end;

答案 1 :(得分:5)

使用本地程序:

declare

  procedure drop_constraint(i_table_name in varchar2, i_column_name in varchar2)
  is
    l_constr_name varchar2(255 char);
  begin
    SELECT x.constraint_name into fName FROM all_constraints x
    JOIN all_cons_columns c ON c.table_name = x.table_name AND c.constraint_name = x.constraint_name
    WHERE x.table_name = i_table_name AND x.constraint_type = 'R' AND c.column_name = i_column_name;

    execute immediate 'alter table ' || i_table_name || ' drop constraint ' || l_constr_name;

  exception
    when NO_DATA_FOUND then
      null; -- ignore or print message
  end drop_constraint;

begin
   drop_constraint('MY_TABLE_NAME', 'MY_COLUMN_NAME');
   drop_constraint('OTHER_TABLE_NAME', 'OTHER_COLUMN_NAME');
end;
/