SQL DROP TABLE 外键约束

如果我想像这样删除数据库中的所有表,它会处理外键约束吗?如果没有,我该如何处理?

If I want to delete all the tables in my database like this, will it take care of the foreign key constraint? If not, how do I take care of that first?

GO
IF OBJECT_ID('dbo.[Course]','U') IS NOT NULL
    DROP TABLE dbo.[Course]
GO
IF OBJECT_ID('dbo.[Student]','U') IS NOT NULL
    DROP TABLE dbo.[Student]

推荐答案

不,如果确实有外键引用它,这不会删除您的表.

No, this will not drop your table if there are indeed foreign keys referencing it.

要获取引用您的表的所有外键关系,您可以使用此 SQL(如果您使用的是 SQL Server 2005 及更高版本):

To get all foreign key relationships referencing your table, you could use this SQL (if you're on SQL Server 2005 and up):

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

如果有的话,在这里使用这个语句,您可以创建 SQL 语句来实际删除这些 FK 关系:

and if there are any, with this statement here, you could create SQL statements to actually drop those FK relations:

SELECT 
    'ALTER TABLE [' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '].[' + OBJECT_NAME(parent_object_id) + 
    '] DROP CONSTRAINT [' + name + ']'
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

相关文章