如何知道在删除之前是否在其他表中引用了表中的行?

时间:2014-06-25 04:43:02

标签: sql sql-server foreign-keys

我有查找表,其记录在其他表中被引用。例如,国家/地区查询表和用户表从国家/地区表中引用国家/地区ID。

我想知道,我如何获取其他表中的引用和所有行的数量,这些行具有国家/地区ID的记录。

如果在其他任何地方找到行的引用,我需要向用户显示该记录被引用的警告,并且无法删除,并列出网格中所有引用的行。

我在

看到过类似的话题

SQL Server: how to know if any row is referencing the row to delete

但答案根本没有帮助,并给出了错误。

5 个答案:

答案 0 :(得分:1)

如果您将引用作为外键,那么sqlserver可以通过Viewing dependensy轻松帮助您,您只需选择查询get all table

select * from countrytable where countryid in
(select countryid from usertable )

select * from countrytable  c
inner join usertable u on c.countryid = u.countryid 

答案 1 :(得分:0)

DECLARE @TableName sysname = 'YourTable'

DECLARE @Command VARCHAR(MAX) 

SELECT @Command = isnull(@Command + ' UNION ALL ', '') + 
       'Select count(*) ,''' + SCHEMA_NAME(obj.schema_id)+'.'+OBJECT_NAME(fkc.parent_object_id) + ''' '+
       'From ' + SCHEMA_NAME(obj.schema_id)+'.'+OBJECT_NAME(fkc.parent_object_id) + ' '+
       'Where ' + col.name+ ' IS NOT NULL' 
from sys.foreign_key_columns fkc
INNER JOIN sys.columns col on fkc.parent_object_id = col.object_id and fkc.parent_column_id = col.column_id
INNER JOIN sys.objects obj ON obj.object_id = col.object_id
where object_name(referenced_object_id) = @TableName

execute (@Command)

答案 2 :(得分:0)

您可以使用合并

 Merge countrytable  as c
using usertable as t on t.cid = c.cid
when not matched then delete 

答案 3 :(得分:0)

还有一种更有效的方法

 ON DELETE NO ACTION

如果引用了一行,它将抛出一个错误,它被其他表引用,这是您的确切要求。

答案 4 :(得分:0)

您可以使用此

找到参考资料
SELECT  *
FROM    Countries C
WHERE   EXISTS (SELECT 1 FROM Users U WHERE U.CountryID = C.CountryID)