Unable to delete the table due to SQL Resolution, prompting that the table is referenced by a foreign key constraint

Source: Internet
Author: User
The SQL statement cannot be used to delete a table. The system prompts that the table is referenced by a foreign key constraint. For more information, see.

The SQL statement cannot be used to delete a table. The system prompts that the table is referenced by a foreign key constraint. For more information, see.

The Drop table command is used to delete all rows in a table or table. The syntax format is:

Drop table "tablename"

The following is an example:

Drop table employee;

To delete the entire table (including all rows), you can use the drop table command and add tablename. The Drop table command is different from deleting all records in the table:

The prompt "the object 'Orders cannot be deleted because the object is being referenced by a foreign key constraint" is displayed. The reason is that the object cannot be deleted because it is referenced by FOREIGN keys of other tables, in this case, you only need to find the tables whose Foreign keys reference the fields of the table. System functions can be used to solve (SQL Server system functions provide excellent functions that can replace us in finding and solving many problems ).

The Code is as follows:

Select
Fk. name, fk. object_id, OBJECT_NAME (fk. parent_object_id) as referenceTableName
From sys. foreign_keys as fk
Join sys. objects as o on fk. referenced_object_id = o. object_id
Where o. name = 'referenced table name'

The preceding SQL statement can obtain the foreign key references to a table and display the table name of the foreign key table. You can delete a foreign key by executing the following statement using the table name and foreign key name of the foreign key table.


Alter table dbo. Name of the referenced table drop constraint foreign key name

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.