简体   繁体   English

如何在 sql 服务器中找到所有包含给定表主键外键的表?

[英]How do I find all the tables which contains foreign key for given table primary key in sql server?

I am trying to search all the tables from database which contains foreign key of given(specific) table's primary key in sql server.我正在尝试从数据库中搜索所有表,其中包含 sql 服务器中给定(特定)表主键的外键。 Please help.请帮忙。

You can use this built-in stored procedure to search all foreign keys for the given table您可以使用此内置存储过程来搜索给定表的所有外键

EXEC sp_fkeys 'TableName'

If this doesn't suit your needs, you can try 10 other ways on this page - https://database.guide/11-ways-return-foreign-keys-sql-server-database-t-sql/如果这不适合您的需要,您可以在此页面上尝试 10 种其他方法 - https://database.guide/11-ways-return-foreign-keys-sql-server-database-t-sql/

Try this..尝试这个..

SELECT
  sys.columns.name AS ColumnName,
  tables.name AS TableName
FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = tables.object_id
WHERE
  sys.columns.name = 'ForeignKeyColumnName'

This should be a good starting point:这应该是一个很好的起点:

select object_name(parent_object_id)
from sys.foreign_keys
where referenced_object_id = object_id('ParentTable');

This doesn't take into account that the FK is specifically referencing your table's PK.这没有考虑到 FK 专门引用了您的表的 PK。 If the above doesn't narrow it down enough, start pulling in sys.foreign_key_columns .如果以上内容不足以缩小范围,请开始拉入sys.foreign_key_columns I'll leave that as an exercise for the reader.我将把它作为练习留给读者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在外键指向其他表主键的JOIN 2表中返回SQL中具有该主键的所有行? - How to to JOIN 2 tables with foreign key pointing to other table primary key to return all the row that have such primary key in SQL? 如何删除表中的记录,该表的主键在另一个表中被引用为外键? - How do I delete a record in a table which has a primary key referenced in another table as foreign key? SQL PHP如何基于另一个表的主键更新外键? - SQL PHP How do I update a foreign key based on the primary key of another table? 外键SQL:如何将一个表中的两个属性引用到在另一个表中包含3列的复合主键? - Foreign Key SQL: How can I reference two attributes in one table to a composite primary key that contains 3 columns in the other table? 创建两个具有相同主键的子类型(或子)表,该主键也是父表的外键 sql - Create Two Subtype (or child) tables with same primary key which is also a foreign key to the parent table sql 如何将 2 个表连接到包含主键的第三个表? - How do I join 2 tables to a third one which contains the primary key? 如何在Sql Server 2000中删除表上的所有外键约束? - How do I drop all foreign-key constraints on a table in Sql Server 2000? 如何为sql server 2012中的另一个表中的每个父主键选择一个表的给定行数? - How do I select a given number of rows for one table for each parent primary key in another table in sql server 2012? 如何为SQL Server中的所有表添加主键? - How to add a primary key to all tables in SQL Server? 如何查找表A的主键具有外键约束的表的列表? - How to find list of tables that are having foreign key contraint for primary key of Table-A?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM