Lister toutes les contraintes de clé étrangère d’une base de données

Voici un petit snippet permettant d’obtenir la liste de toutes les contraintes de clé étrangère d’une base de données avec :
– le nom de la contrainte,
Рle nom de la table r̩f̩ren̤ante,
Рle nom de la colonne r̩f̩ren̤ante dans la table r̩f̩ren̤ante,
Рle nom de la table r̩f̩renc̩e,
Рle nom de la colonne r̩f̩renc̩e dans la table r̩f̩renc̩e.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-------------------------------
-- Nicolas SOUQUET - 09/11/2009
-------------------------------
SELECT    PS.name + '.' + PT.name AS parent_table_name
    , PC.name AS parent_column_name
    , RS.name + '.' + RT.name AS referenced_table_name
    , RC.name AS referenced_column_name
    , FK.name AS foreign_key_name
FROM    sys.schemas AS PS
INNER JOIN  sys.foreign_keys AS FK
      ON PS.schema_id = FK.schema_id
INNER JOIN  sys.foreign_key_columns AS FKC
      ON FK.object_id = FKC.constraint_object_id
INNER JOIN  sys.tables AS PT
      ON FK.parent_object_id = PT.object_id
INNER JOIN  sys.columns AS PC
      ON FKC.parent_object_id = PC.object_id
      AND FKC.parent_column_id = PC.column_id
INNER JOIN  sys.tables AS RT
      ON FK.referenced_object_id = RT.object_id
INNER JOIN  sys.columns AS RC
      ON FKC.referenced_object_id = RC.object_id
      AND FKC.referenced_column_id = RC.column_id
INNER JOIN  sys.schemas AS RS
      ON RT.schema_id = RS.schema_id
WHERE    1 = 1
--AND    RS.name = 'dbo'
--AND    PS.name = 'dbo'
--AND    PT.name = 'maTable'
AND    RT.name = 'maTable'
--AND    RC.name = 'maColonne'
--AND    FK.name = 'maContrainte'
--ORDER BY  parent_table_name
ORDER BY  foreign_key_name

Bonne gestion de l’intégrité référentielle !

ElSüket

Laisser un commentaire