/*
Server:		sun791aps.sunstore.ch
Format:		GCM 
Business:	TPPHAR
type:		PROD
Version:	21.3.11111.00064

02.11.2022, TSC
*/
USE Arizona;


SELECT
    SCHEMA_NAME(tab.SCHEMA_ID) + '.' + tab.name       AS [table]
   ,col.column_id
   ,col.name                                          AS column_name
   ,CASE
        WHEN fk.OBJECT_ID IS NOT NULL THEN '>-'
        ELSE NULL
    END                                               AS rel
   ,SCHEMA_NAME(pk_tab.SCHEMA_ID) + '.' + pk_tab.name AS primary_table
   ,pk_col.name                                       AS pk_column_name
   ,fk_cols.constraint_column_id                      AS NO
   ,fk.name                                           AS fk_constraint_name
FROM sys.tables                             tab
    INNER JOIN sys.columns                  col
        ON col.OBJECT_ID             = tab.OBJECT_ID
    LEFT OUTER JOIN sys.foreign_key_columns fk_cols
        ON fk_cols.parent_object_id  = tab.OBJECT_ID
        AND fk_cols.parent_column_id = col.column_id
    LEFT OUTER JOIN sys.foreign_keys        fk
        ON fk.OBJECT_ID              = fk_cols.constraint_object_id
    LEFT OUTER JOIN sys.tables              pk_tab
        ON pk_tab.OBJECT_ID          = fk_cols.referenced_object_id
    LEFT OUTER JOIN sys.columns             pk_col
        ON pk_col.column_id          = fk_cols.referenced_column_id
        AND pk_col.OBJECT_ID         = fk_cols.referenced_object_id
WHERE fk.OBJECT_ID IS NOT NULL
--AND SCHEMA_NAME(tab.SCHEMA_ID) = 'dbo'
--AND tab.name='customer'
ORDER BY SCHEMA_NAME(tab.SCHEMA_ID) + '.' + tab.name
        ,col.column_id;