How can I list all foreign keys referencing a given table in SQL Server?

后端 未结 26 2660
梦毁少年i
梦毁少年i 2020-11-22 07:13

I need to remove a highly referenced table in a SQL Server database. How can I get a list of all the foreign key constraints I will need to remove in order to drop the tabl

26条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 08:07

    The following solution work for me:

    --Eliminar las llaves foraneas
    declare @query varchar(8000)
    declare cursorRecorrerTabla cursor for
    
    SELECT  'ALTER TABLE [PoaComFinH].['+sch.name+'].['+referencingTable.Name+'] DROP CONSTRAINT ['+foreignKey.name+']' 'query'
    FROM PoaComFinH.sys.foreign_key_columns fk
    JOIN PoaComFinH.sys.tables referencingTable ON fk.parent_object_id = referencingTable.object_id
    JOIN PoaComFinH.sys.schemas sch ON referencingTable.schema_id = sch.schema_id
    JOIN PoaComFinH.sys.objects foreignKey ON foreignKey.object_id = fk.constraint_object_id
    JOIN PoaComFinH.sys.tables referencedTable ON fk.referenced_object_id = referencedTable.object_id
    
    
    --3ro. abrir el cursor.
    open cursorRecorrerTabla
    fetch next from cursorRecorrerTabla
    into @query
    while @@fetch_status = 0
    begin
    --inicio cuerpo del cursor
        print @query
        exec(@query)
    --fin cuerpo del cursor
    fetch next from cursorRecorrerTabla
    into @query
    end
    --cerrar cursor
    close cursorRecorrerTabla
    deallocate cursorRecorrerTabla
    

提交回复
热议问题