我需要获取主键列的名称。
在输入中,我只有表名。
答案 0 :(得分:163)
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以大写形式存储表名。
答案 1 :(得分:18)
与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'
);
答案 2 :(得分:2)
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是主要关键名称)
答案 3 :(得分:1)
试用此代码 在这里,我在oracle中创建了一个获取主键列的表,称为test然后查询
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;
答案 4 :(得分:0)
将以下脚本保存为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