查找列是否具有唯一约束

dmv*_*nna 7 sql oracle

在假设的场景中,我是没有表创建权限的用户.我想知道表中的列是否具有UNIQUE CONSTRAINT.是否有可能在DICTIONARY中查找?我该怎么办呢?

Seb*_*anH 7

这里给出的两个答案都错过了一种方法来强制列的唯一性:通过创建唯一索引(不在列上定义唯一约束).如果您不熟悉此选项,请参阅这两个链接(,).

除了唯一约束检查之外,还应执行此检查:

select count(*) from
USER_IND_COLUMNS cols
where cols.table_name='YOUR_TABLE_NAME'
and cols.COLUMN_NAME='YOUR_COLUMN';
Run Code Online (Sandbox Code Playgroud)

要检查唯一约束,请使用已提供的方法:

select count(*) cnt 
from user_constraints uc
where uc.table_name='YOUR_TABLE_NAME'
and uc.constraint_type='U';
Run Code Online (Sandbox Code Playgroud)

或者您也可以查看ALL_CONSTRAINTSALL_IND_COLUMNS查看.


Daz*_*zaL 5

对于独特的约束,您可以执行以下操作:

select cons.constraint_type, 
       all_cols.owner, all_cols.constraint_name, 
       all_cols.table_name, 
       all_cols.column_name, 
       all_cols.position
  from all_cons_columns col
       inner join all_cons_columns all_cols
               on col.owner = all_cols.owner
              and col.constraint_name = all_cols.constraint_name
       inner join all_constraints cons
               on col.owner = cons.owner
              and col.constraint_name = cons.constraint_name
 where col.owner = 'SCHEMA'
   and col.table_name = 'FOO'
   and col.column_name = 'ID'
   and cons.constraint_type in ('U', 'P')
 order by owner, constraint_name, position;
Run Code Online (Sandbox Code Playgroud)

设置感兴趣的所有者,表格和列,它将显示涵盖该列的所有约束

请注意,这不会显示列上存在唯一索引的所有情况(因为它可能在没有约束的情况下具有唯一索引).

例:

SQL> create table foo(id number, id2 number, constraint foo_con unique(id, id2), constraint foo_con2 unique(id));

Table created.
Run Code Online (Sandbox Code Playgroud)

现在列出涵盖的所有约束id:

SQL> col column_name format a20
SQL> col constraint_name format a20
SQL> col table_name format a15
SQL> select cons.constraint_type,
  2         all_cols.owner, all_cols.constraint_name,
  3         all_cols.table_name,
  4         all_cols.column_name,
  5         all_cols.position
  6    from all_cons_columns col
  7         inner join all_cons_columns all_cols
  8                 on col.owner = all_cols.owner
  9                and col.constraint_name = all_cols.constraint_name
 10         inner join all_constraints cons
 11                 on col.owner = cons.owner
 12                and col.constraint_name = cons.constraint_name
 13   where col.owner = user
 14     and col.table_name = 'FOO'
 15     and col.column_name = 'ID'
 16     and cons.constraint_type in ('U', 'P')
 17   order by owner, constraint_name, position;

C OWNER                          CONSTRAINT_NAME      TABLE_NAME      COLUMN_NAME            POSITION
- ------------------------------ -------------------- --------------- -------------------- ----------
U DTD_TRADE                      FOO_CON              FOO             ID                            1
U DTD_TRADE                      FOO_CON              FOO             ID2                           2
U DTD_TRADE                      FOO_CON2             FOO             ID                            1
Run Code Online (Sandbox Code Playgroud)