我想知道如何通过运行SQL查询来发现我的SQL Server数据库中哪些表彼此相关。
例如,假设我有2个多对多关系和3个用一些随机值初始化的表。
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)
);
我想运行一个参数化查询,其输出类似于:
使用参数'A':
MM_TAB | REL_TAB
------------------
AB | B
AC | C
使用参数'B':
MM_TAB | REL_TAB
------------------
AB | A
使用参数“C”:
MM_TAB | REL_TAB
------------------
AC | A
我该怎么做?
答案 0 :(得分:1)
检查出来:
我使用SQL Server 2014创建了表和关系:
create database relation
use relation
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 foreign key references A(pk),
b_pk int not null foreign key references B(pk),
primary key(a_pk, b_pk)
);
create table AC
(
a_pk int not null foreign key references A(pk),
c_pk int not null foreign key references C(pk),
primary key(a_pk, c_pk)
);
然后您可以使用此查询来查找相关表:
use relation
go
DECLARE @table_param NVARCHAR(2)='A';
with rel as(
SELECT
K_Table = FK.TABLE_NAME,
--FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME
--PK_Column = PT.COLUMN_NAME,
--Constraint_Name = C.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
wHERE PK.TABLE_NAME = @table_param
)
SELECT
K_Table = FK.TABLE_NAME,
--FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME
--PK_Column = PT.COLUMN_NAME,
--Constraint_Name = C.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
WHERE FK.TABLE_NAME IN(SELECT R.K_Table FROM REL R)