问题
I am implementing a search functionality from UI for this I want to give a drop down of column names which have unique constraints along with any primary key column if present, so user can search with any of these selected column relate data. I have searched for such query but haven't found
Something like:
SELECT COLUMN_NAMEs FROM TABLE WHERE CONSTRAINTS UNIQUE OR PRIMARY
Is there any query to achieve this ...
回答1:
USER_CONSTRAINTS would return foreign keys also. You need only primary and unique keys. But uniqueness can be achieved via unique index too. It won't be shown in constraints list. You need to watch USER_INDEXES view. The good point is that primary and unique keys create corresponding unique indexes. So, it's necessary and sufficient to check USER_INDEXES.
UPD: see Lalit Kumar B's comment.
select c.COLUMN_NAME
from USER_INDEXES i, USER_IND_COLUMNS c
where i.TABLE_NAME = 'YOUR_TABLE'
and i.UNIQUENESS = 'UNIQUE'
and i.TABLE_NAME = c.TABLE_NAME
and i.INDEX_NAME = c.INDEX_NAME
union
select cc.COLUMN_NAME
from USER_CONSTRAINTS con, USER_CONS_COLUMNS cc
where con.TABLE_NAME = 'YOUR_TABLE'
and con.CONSTRAINT_TYPE in ( 'U', 'P' )
and con.TABLE_NAME = cc.TABLE_NAME
and con.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
回答2:
You need to look at USER_CONS_COLUMNS view. And to get the constraint_type, you could join it with USER_CONSTRAINTS.
SQL> desc user_cons_columns;
Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(128)
CONSTRAINT_NAME NOT NULL VARCHAR2(128)
TABLE_NAME NOT NULL VARCHAR2(128)
COLUMN_NAME VARCHAR2(4000)
POSITION NUMBER
SQL>
For example,
SQL> column owner format a6
SQL> column constraint_name format a10
SQL> column table_name format a10
SQL> column column_name format a10
SQL> SELECT A.owner,
2 A.constraint_name,
3 A.table_name,
4 A.column_name,
5 b.constraint_type
6 FROM user_cons_columns A,
7 user_constraints b
8 WHERE A.owner =b.owner
9 AND A.constraint_name=b.constraint_name
10 AND A.table_name =b.table_name;
OWNER CONSTRAINT TABLE_NAME COLUMN_NAM C
------ ---------- ---------- ---------- -
SCOTT FK_DEPTNO EMP DEPTNO R
SCOTT PK_DEPT DEPT DEPTNO P
SCOTT PK_EMP EMP EMPNO P
SQL>
来源:https://stackoverflow.com/questions/28404046/getting-unique-constraint-column-names-from-oracle-database