本文介绍了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')
这篇关于SQL DROP TABLE 外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!