Sql-Server
查看外鍵約束,以便我可以刪除表
我已經複製了一個我正在開發的數據庫,因此我可以為我的新版本更改其設計的一些關鍵元素。
我想從數據庫中完全刪除一些表,但是由於一些外鍵約束我不能。
1)如何查看表上存在的外鍵約束?
2)如何刪除外鍵和表?
我正在查看 2008R2 的此文件,但我不理解它sys.foreign_keys
以下是如何為您要刪除的所有表格生成@Shark 顯示的腳本。假設您有以下表格:
USE tempdb; GO CREATE TABLE dbo.z(z INT PRIMARY KEY); -- we won't delete this one CREATE TABLE dbo.a ( a INT PRIMARY KEY FOREIGN KEY REFERENCES dbo.z(z) ); CREATE TABLE dbo.b ( b INT PRIMARY KEY, a INT FOREIGN KEY REFERENCES dbo.a(a) ); CREATE TABLE dbo.c ( c INT PRIMARY KEY, b INT FOREIGN KEY REFERENCES dbo.b(b), a INT FOREIGN KEY REFERENCES dbo.a(a) ); -- we won't drop this table either, but we'll need to drop -- the constraint: CREATE TABLE dbo.d ( d INT, c INT FOREIGN KEY REFERENCES dbo.c(c) );
但我們只想刪除 a、b 和 c。
-- load the tables you want to delete into a table variable: DECLARE @tables_to_delete TABLE (t NVARCHAR(512)); INSERT @tables_to_delete VALUES('dbo.a'),('dbo.b'),('dbo.c'); DECLARE @sql NVARCHAR(MAX) = N''; -- build a list of the foreign keys you'll have to drop first: SELECT @sql += CHAR(13) + CHAR(10) + N'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(f.parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(f.parent_object_id)) + ' DROP CONSTRAINT ' + QUOTENAME(f.name) + ';' FROM sys.foreign_keys AS f INNER JOIN @tables_to_delete AS t ON f.referenced_object_id = OBJECT_ID(t.t); -- then the DROP TABLE commands: SELECT @sql += CHAR(13) + CHAR(10) + N'DROP TABLE ' + t + ';' FROM @tables_to_delete; PRINT @sql; -- EXEC sp_executesql @sql;
結果(如果你執行它,約束名稱看起來會有所不同):
ALTER TABLE [dbo].[b] DROP CONSTRAINT [FK__b__a__2D27B809]; ALTER TABLE [dbo].[c] DROP CONSTRAINT [FK__c__a__30F848ED]; ALTER TABLE [dbo].[c] DROP CONSTRAINT [FK__c__b__300424B4]; ALTER TABLE [dbo].[d] DROP CONSTRAINT [FK__d__c__32E0915F]; DROP TABLE dbo.a; DROP TABLE dbo.b; DROP TABLE dbo.c;
當您對結果感到滿意時,請取消註釋該
EXEC
行。(請注意,如果腳本非常大,您將無法在使用時完整地驗證腳本
sp_executesql
。)