Drop Foreign Key without knowing the name of the constraint?

You can find the name of the constraint in INFORMATION_SCHEMA.TABLE_CONSTRAINTS

select CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where TABLE_NAME = 'Table1'

A SQL Server option:

DECLARE @foreignkey varchar(100)
DECLARE @tablename varchar(100)
DECLARE @command nvarchar(1000)

DECLARE db_cursor CURSOR FOR
SELECT fk.name, t.name
FROM sys.foreign_keys fk
JOIN sys.tables t ON t.object_id = fk.parent_object_id
WHERE t.name IN (
    'table_1_name_here',
    'table_2_name_here'
)

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @foreignkey, @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @command = 'ALTER TABLE ' + @tablename + ' DROP CONSTRAINT ' + @foreignkey
    EXECUTE(@command)
    FETCH NEXT FROM db_cursor INTO @foreignkey, @tablename
END
CLOSE db_cursor
DEALLOCATE db_cursor

The SQL selects all the constraints for the tables you care about into a cursor and drops them one by one. All you need to know are the names of the tables you want them dropped from.


Expanding on the answers since I ran into some gotchas. Also, I had 2 foreign keys declared, so I added an optional key to keep, if it's null it'll just be ignored:

declare @name varchar(255),
     @table varchar(255) = 'mytable',
     @column varchar(255) = 'mykeycolumn',
     @validkey varchar(255) =  'mykeyIwanttokeep'

SELECT @name = CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @table
    AND COLUMN_NAME =  @column
    AND (CONSTRAINT_NAME != @validkey or @validkey is null)

declare @sql varchar(1023) = 'alter table ' + @table + ' drop ' + @name 

exec (@sql)

Similar to Ed's Answer but you can use this to select the key name based on the table and column name.

That way you can run it in a script or maybe as a subquery to drop the constraint.

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME =  'post'
AND COLUMN_NAME =  'userID'

Tags:

Sql Server