Respostas:
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;
Certifique-se de que 'TABLE_NAME' esteja em maiúsculas, pois o Oracle armazena os nomes das tabelas em maiúsculas.
q
.
O mesmo que a resposta de 'Richie', mas um pouco mais conciso.
Consultar apenas as restrições do usuário
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'
);
Consulta para todas as restrições
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'
);
user_constraints
por all_constraints
.
SELECT owner, column_name, position FROM all_cons_columns WHERE (owner, constraint_name) in (SELECT owner, constraint_name FROM all_constraints WHERE UPPER(table_name) = UPPER('&tableName') AND CONSTRAINT_TYPE = 'P') order by owner, position;
Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;
(Isso listará a chave primária e, em seguida)
Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’;
(Isso fornecerá a coluna, aqui PK_XYZ é o nome da chave primária)
Tente este código Aqui eu criei uma tabela para obter a coluna de chave primária no oracle que é chamada de teste e consulta
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;
Salve o seguinte script como algo como 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');
Ele pode então ser chamado usando
@findPK