I would like to know how to discover which tables are related each other in my SQL Server database by running a SQL query.
As example, suppose I have 2 many-to-many relations and 3 tables initialized with some random values.
create table A (pk int not null primary key identity, A int);
create table B (pk int not null primary key identity, B int);
create table C (pk int not null primary key identity, C int);
create table AB
(
a_pk int not null references A,
b_pk int not null references B,
primary key(a_pk, b_pk)
);
create table AC
(
a_pk int not null references A,
c_pk int not null references C,
primary key(a_pk, c_pk)
);
I would like to run a parametrized query having as output something like:
With parameter 'A':
MM_TAB | REL_TAB
------------------
AB | B
AC | C
With parameter 'B':
MM_TAB | REL_TAB
------------------
AB | A
With parameter 'C':
MM_TAB | REL_TAB
------------------
AC | A
How can I do that?