如果有任何行引用要通过FK删除的行,则无法删除该行。
在执行DELETE语句之前是否可以知道是否有任何行在引用要删除的行?
该脚本将显示所有具有引用您要删除的行的行的表:
declare @RowId int = 1 declare @TableName sysname = 'ParentTable' declare @Command varchar(max) select @Command = isnull(@Command + ' union all ', '') + 'select ''' + object_name(parent_object_id) + ''' where exists(select * from ' + object_name(parent_object_id) + ' where ' + col.name+ ' = ' + cast(@RowId as varchar) + ')' from sys.foreign_key_columns fkc join sys.columns col on fkc.parent_object_id = col.object_id and fkc.parent_column_id = col.column_id where object_name(referenced_object_id) = @TableName execute (@Command)
假定外键不是复合键。