如何在Oracle中获得主键列?
我需要获取主键列的名称。
在input中,我只有表名。
SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TABLE_NAME' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position;
请确保“TABLE_NAME”是大写,因为Oracle以大写forms存储表名。
和“Richie”的答案一样,但更简洁一些。
-
仅查询用户约束
SELECT column_name FROM all_cons_columns WHERE constraint_name = ( SELECT constraint_name FROM user_constraints WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P' );
-
查询所有约束
SELECT column_name FROM all_cons_columns WHERE constraint_name = ( SELECT constraint_name FROM all_constraints WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P' );
Select constraint_name,constraint_type from user_constraints where table_name** **= 'TABLE_NAME' ;
(这将列出主键然后)
Select column_name,position from user_cons_cloumns where constraint_name='PK_XYZ';
(这会给你的列,这里PK_XYZ是主键名)
将下面的脚本保存为findPK.sql。
set verify off accept TABLE_NAME char prompt 'Table name>' SELECT cols.column_name FROM all_constraints cons NATURAL JOIN all_cons_columns cols WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');
然后可以使用它
@findPK
试试这个代码在这里我创build了一个表,用于获取oracle中的主键列,称为testing然后查询
create table test ( id int, name varchar2(20), city varchar2(20), phone int, constraint pk_id_name_city primary key (id,name,city) ); SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TEST' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position;