DROP TABLE - Foreign Key Issue

Trying to delete some tables but they won’t because of foreign key constraints. Is there a way to override this?
IE A DROP TABLE command that drops irrespective etc?
or do I need to do what I am doing IE find the constraints remove them then delete as follows?

To get Keys I’m running:
SELECT *
FROM Calibration_V4_diff.sys.foreign_keys
WHERE referenced_object_id = object_id('Calibration_V4_diff.dbo.tblCompanies')

To get foreign keys like:

Array ( [name] => tblAddresses$tblCompaniestblAddresses [object_id] => 647777465 [principal_id] => [schema_id] => 1 [parent_object_id] => 802206008 [type] => F [type_desc] => FOREIGN_KEY_CONSTRAINT [create_date] => DateTime Object ( [date] => 2023-05-30 15:27:34.010000 [timezone_type] => 3 [timezone] => Europe/Minsk ) [modify_date] => DateTime Object ( [date] => 2023-05-30 15:27:34.010000 [timezone_type] => 3 [timezone] => Europe/Minsk ) [is_ms_shipped] => 0 [is_published] => 0 [is_schema_published] => 0 [referenced_object_id] => 439776724 [key_index_id] => 1 [is_disabled] => 0 [is_not_for_replication] => 0 [is_not_trusted] => 1 [delete_referential_action] => 0 [delete_referential_action_desc] => NO_ACTION [update_referential_action] => 0 [update_referential_action_desc] => NO_ACTION [is_system_named] => 0 )

Then altering the table based on the key “name” as above:

query: ALTER TABLE Calibration_V4_diff.dbo.tblCompanies DROP CONSTRAINT [tblAddresses$tblCompaniestblAddresses];

It’s not recognized IE responds:

Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 3733 [code] => 3733 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Constraint 'tblAddresses$tblCompaniestblAddresses' does not belong to table 'tblCompanies'. [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Constraint 'tblAddresses$tblCompaniestblAddresses' does not belong to table 'tblCompanies'. ) [1] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 3727 [code] => 3727 [2] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Could not drop constraint. See previous errors. [message] => [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Could not drop constraint. See previous errors. ) )

Many Thanks :slight_smile:

1 Like