How to find what foreign key references an index on table

前端 未结 3 957
灰色年华
灰色年华 2021-01-04 07:32

I have a non clustered index I would like to drop (it is a duplicate of the clustered index). However, it is being used by a foreign key constraint. I would like to be abl

3条回答
  •  难免孤独
    2021-01-04 07:57

    This will tell you the tables, the foreign key and the columns involved:

    select f.name
      , parentTable = o.name
      , parentColumn = c.name
      , foreignTable = ofr.name
      , foreignColumn = cfr.name
    from sys.foreign_keys f
      inner join sys.foreign_key_columns fc on f.object_id = fc.constraint_object_id
      inner join sys.objects o on fc.parent_object_id = o.object_id
      inner join sys.columns c on fc.parent_column_id = c.column_id
        and o.object_id = c.object_id
      inner join sys.objects ofr on fc.referenced_object_id = ofr.object_id
      inner join sys.columns cfr on fc.referenced_column_id = cfr.column_id
        and ofr.object_id = cfr.object_id
      inner join sys.indexes i on ofr.object_id = i.object_id
    where i.name = 'MyIndex'
    

    SQL Fiddle with demo.

提交回复
热议问题