If you want to delete a foreign key based on a given table name and column name in T-SQL, you can use the following code snippet:

Full table name = [MySchema1].[MyTable1]

Full column name = [MyColumn1]

declare @TableName varchar(255)
set @TableName = '[MySchema1].[MyTable1]'

declare @ColumnName varchar(255)
set @ColumnName = 'MyColumn1'

declare @TabelObjectId int
set @tabelObjectId = Object_ID(@TableName)

declare @ForeignKeyObjectId int
select        @ForeignKeyObjectId = fc.constraint_object_id
from        sys.foreign_key_columns fc
inner join    sys.columns c  on  c.object_id = parent_object_id and c.column_id = fc.parent_column_id
where        fc.parent_object_id = @tabelObjectId and c.name = @ColumnName

declare @ForeignKeyName int
set @ForeignKeyName = (select name from sys.objects where object_id = @ForeignKeyObjectId)

if object_id(@ForeignKeyObjectId) is not null
    exec('alter table ' + @TableName + ' drop constraint ' + @ForeignKeyName)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts