Oracle sql,更改约束而不指定其名称

时间:2018-04-19 08:11:59

标签: oracle dynamic-sql ddl alter-table

我想在oracle数据库中重命名一个约束,而不指定它的名字,而是选择它的名字。我想做这样的事情:

ALTER TABLE O4Y_USER RENAME CONSTRAINT
    (SELECT constraint_name
            FROM user_constraints
            WHERE table_name    = 'O4Y_USER'
            AND constraint_type = 'P'
     ) TO 'O4Y_USER_PK';

它无效,我有以下错误

enter image description here

单独选择,运行良好,它返回正确的值。如何正确处理alter语句?

2 个答案:

答案 0 :(得分:3)

您可以使用动态SQL。类似的东西:

DECLARE
  p_constraint_name VARCHAR2(30);
  p_sql             VARCHAR2(4000);
BEGIN
  SELECT constraint_name
  INTO   p_constraint_name
  FROM   user_constraints
  WHERE  table_name    = 'O4Y_USER'
  AND    constraint_type = 'P';

  p_sql := 'ALTER TABLE O4Y_USER RENAME CONSTRAINT "'
           || p_constraint_name
           || '" TO ''O4Y_USER_PK''';

  DBMS_OUTPUT.PUT_LINE( p_sql );
  EXECUTE IMMEDIATE p_sql;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE( 'Constraint not found!' );
END;
/

答案 1 :(得分:2)

使用SQL * Plus或类似命令行工具的方法相同。

SQL> create table t ( x int primary key );

Table created.

SQL>
SQL> col cname new_value x
SQL>
SQL> SELECT constraint_name cname
  2  FROM   user_constraints
  3  WHERE  table_name    = 'T'
  4  AND    constraint_type = 'P';

CNAME
----------------------------------------------------------------------
SYS_C0068724

SQL>
SQL> ALTER TABLE t RENAME CONSTRAINT &&x to my_new_name;
old   1: ALTER TABLE t RENAME CONSTRAINT &&x to my_new_name
new   1: ALTER TABLE t RENAME CONSTRAINT SYS_C0068724 to my_new_name

Table altered.