views:

80

answers:

1

I need to rename a constraint in an Oracle databse, but I don't know the old name at design-time.

What I would like to do is this:

declare
  vOldName string;
begin
  select CONSTRAINT_NAME 
  into   vOldName 
  from   user_constraints 
  where  TABLE_NAME='AGREEMENT' and CONSTRAINT_TYPE='R';

  alter table Agreement rename constraint vOldName to AGREEMENT_FK1; 
end;

but I get the error message "PLS-00103: Encountered the symbol "ALTER" when expecting one of the following: begin case ".

How do I solve this problem?

+4  A: 

Use dynamic PL/SQL:

declare
  vOldName user_constraints.constraint_name%TYPE;
begin
  select CONSTRAINT_NAME 
  into   vOldName 
  from   user_constraints 
  where  TABLE_NAME='AGREEMENT' and CONSTRAINT_TYPE='R';

  execute immediate 'alter table Agreement rename constraint ' 
      || vOldName || ' to AGREEMENT_FK1'; 
end;
Tony Andrews
Great, thanks! Worked like a charm. Had to declare vOldName as varchar, not string, but that was my own mistake :-)
Svein Bringsli
I'll fix that in my answer
Tony Andrews
Also, let me take this oppurtunity to say how BLOODY AWESOME Stack Overflow is. I had the answer to my question within two minutes!! Incredible. It saved me from _many_ hours of web-digging.
Svein Bringsli