我有一个问题,我不确定我是否想得太深,但是问题是我想查询sql server以给我指定外键ID,列名和表的主键。 以下查询为我提供了主键/外键约束,表等。
SELECT
FK = OBJECT_NAME(fkc.constraint_object_id),
Referencing_table = QUOTENAME(OBJECT_SCHEMA_NAME(fkc.parent_object_id))
+ '.' + QUOTENAME(OBJECT_NAME(fkc.parent_object_id)),
Referencing_col = QUOTENAME(pc.name),
Referenced_table = QUOTENAME(OBJECT_SCHEMA_NAME(fkc.referenced_object_id))
+ '.' + QUOTENAME(OBJECT_NAME(fkc.referenced_object_id)),
Referenced_col = QUOTENAME(rc.name),
PK = pk.name
FROM sys.foreign_key_columns AS fkc
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.columns AS rc
ON fkc.referenced_column_id = rc.column_id
AND fkc.referenced_object_id = rc.[object_id]
INNER JOIN (SELECT i.name, fk.[object_id]
FROM sys.indexes AS i
INNER JOIN sys.foreign_keys AS fk
ON i.[object_id] = fk.referenced_object_id
AND i.index_id = fk.key_index_id
) AS pk
ON pk.[object_id] = fkc.constraint_object_id
ORDER BY Referencing_table, FK, fkc.constraint_column_id;
一个简单的表结构就是
create table test.ForeignTable1
(
foreign_key_table_primary_key1 int primary key identity(1,1),
randomdata1 varchar(200) not null
)
create table test.ForeignTable2
(
foreign_key_table_primary_key2 int primary key identity(1,1),
randomdata2 varchar(200) not null
)
create table test.PrimTable
(
primary_key_column int primary key identity(1,1),
ForeignTable1_data int foreign key references test.ForeignTable1(foreign_key_table_primary_key1) ,
ForeignTable2_data int foreign key references test.ForeignTable2(foreign_key_table_primary_key2)
)
对于 PrimTable 中的特定主键,sql语句的期望输出将返回为 test.ForeignTable2 中所有相关的ID,然后返回 test.ForeignTable1 ,并显示它们来自哪个表。
如果我提供1,那么它将为 test.ForeignTable1 返回ID(3,7,12),为 test.ForeignTable2 返回ID(6,4,458,88)。
是否可以查询类似的内容?我也想知道sql server在删除期间如何确定另一个表中有外键约束,从而阻止您删除项目?
答案 0 :(得分:0)
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
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
WHERE PK.TABLE_NAME=@PK_TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
答案 1 :(得分:-1)
只需运行以下内容:
EXEC sp_fkeys @pktable_name = '<your_PK_table_name>'