• My initial thought is using information_schema views or sys tables to enumerate what table/column combinations constitute primary keys, join to any other tables that contains the same column combination, while excluding any tables which already contain a foreign key on those same columns. That would be more comprehensive than the referenced example which seems to assume that primary keys have "ID" in the name and contain only that one column.

    I'm in a new job, so I don't have bandwidth to complete the actual code, but here is some starter code for anyone who wants to mix and bake it:

    SELECT ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME

    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc

    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ku

    ON tc.CONSTRAINT_TYPE = 'PRIMARY KEY'

    AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME

    ORDER BY ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME;

    SELECT ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME

    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc

    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ku

    ON tc.CONSTRAINT_TYPE = 'FOREIGN KEY'

    AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME

    ORDER BY ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME;

    "Do not seek to follow in the footsteps of the wise. Instead, seek what they sought." - Matsuo Basho