I was getting the following error when I was trying to drop a table from SQL. ‘Could not drop object ‘TableName’ because it is referenced by a FOREIGN KEY constraint.’ Ah yes, i need to drop the FOREIGN KEY constraints first before I can drop the table. Here is a quick way to do just that.
First run this script to create the actual SQL code you will be using;
–Drop constraint
SELECT
‘ALTER TABLE ‘ + OBJECT_NAME(parent_object_id) +
‘ DROP CONSTRAINT ‘ + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id(‘Roles’)
Copy and past the SQL script that was created and run that. It will create something like ‘ALTER TABLE TableName DROP CONSTRAINT FK_TableName_OtherTableName’
Now you can drop your table;
–Drop Table
DROP TABLE TableName