23 October, 2012
0 Comments
1 category
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 begin exec('alter table ' + @TableName + ' drop constraint ' + @ForeignKeyName) end
Tags: T-SQL
Category: Uncategorized