如何检查记录的键是否在其他表中用作外键(sql)?

时间:2021-03-30 14:16:42

I have a table that its primary key "ID" field is used in many other table as foreign key.

我有一个表,其主键“ID”字段在许多其他表中用作外键。

How can I realize that a record from this table (for example first record "ID = 1") is used in other table?

如何才能意识到该表中的记录(例如第一个记录“ID = 1”)在其他表中使用?

I don't want to select from all other tables to understand it cause tables are so many and relations either. I searched for a solution, there were no working solutions or I got it wrong. Please help.

我不想从所有其他表中选择来理解它因为表是如此之多和关系。我搜索了一个解决方案,没有可行的解决方案,或者我弄错了。请帮忙。

2 个解决方案

#1


8  

For a Generic way use this and you will get all the tables that have the foreign key, and then u can make a loop to check all tables in list. This way u can add foreign keys and no change in code will be needed...

对于通用方式使用此方法,您将获得具有外键的所有表,然后您可以循环检查列表中的所有表。这样你可以添加外键,不需要改变代码......

SELECT 
sys.sysobjects.name,
sys.foreign_keys.*
FROM 
sys.foreign_keys 
inner join sys.sysobjects on
    sys.foreign_keys.parent_object_id = sys.sysobjects.id
WHERE 
referenced_object_id = OBJECT_ID(N'[dbo].[TableName]') 

#2


2  

You need to join all other tables. Like this:

您需要加入所有其他表。喜欢这个:

select *
from Parents
where
 exists(select * from Children1 where ...)
 or exists(select * from Children2 where ...)
 or exists(select * from Children3 where ...)

If all your FK columns are indexed this will be extremely efficient. You will get nice merge joins.

如果您的所有FK列都被编入索引,这将非常有效。你会得到很好的合并连接。

#1


8  

For a Generic way use this and you will get all the tables that have the foreign key, and then u can make a loop to check all tables in list. This way u can add foreign keys and no change in code will be needed...

对于通用方式使用此方法,您将获得具有外键的所有表,然后您可以循环检查列表中的所有表。这样你可以添加外键,不需要改变代码......

SELECT 
sys.sysobjects.name,
sys.foreign_keys.*
FROM 
sys.foreign_keys 
inner join sys.sysobjects on
    sys.foreign_keys.parent_object_id = sys.sysobjects.id
WHERE 
referenced_object_id = OBJECT_ID(N'[dbo].[TableName]') 

#2


2  

You need to join all other tables. Like this:

您需要加入所有其他表。喜欢这个:

select *
from Parents
where
 exists(select * from Children1 where ...)
 or exists(select * from Children2 where ...)
 or exists(select * from Children3 where ...)

If all your FK columns are indexed this will be extremely efficient. You will get nice merge joins.

如果您的所有FK列都被编入索引,这将非常有效。你会得到很好的合并连接。