Réponses:
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;
Assurez-vous que «TABLE_NAME» est en majuscules car Oracle stocke les noms de table en majuscules.
q
.
Identique à la réponse de «Richie» mais un peu plus concis.
Requête pour les contraintes utilisateur uniquement
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'
);
Requête pour toutes les contraintes
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
par 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’ ;
(Cela listera la clé primaire puis)
Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’;
(Cela vous donnera la colonne, ici PK_XYZ est le nom de la clé primay)
Essayez ce code Ici, j'ai créé une table pour obtenir la colonne de clé primaire dans oracle qui est appelée test, puis requête
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;
Enregistrez le script suivant comme quelque chose comme 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');
Il peut alors être appelé en utilisant
@findPK