use*_*998 5 sql t-sql sql-server foreign-keys sql-drop
我有一个新表,该表具有对许多现有表的外键引用。首次创建新表时,我通过以下方式创建外键:
ALTER TABLE [dbo].[NewTable] WITH CHECK ADD FOREIGN KEY([SectionDatabaseID])
REFERENCES [dbo].[Section] ([SectionDatabaseID])
ALTER TABLE [dbo].[NewTable] WITH CHECK ADD FOREIGN KEY([TermDatabaseID])
REFERENCES [dbo].[Term] ([TermDatabaseID])
Run Code Online (Sandbox Code Playgroud)
上面的方法将使用它自己的自动命名约定为外键约束生成名称。
但是,我想删除新表,因为我需要通过从头开始创建表来进行一些重大修改。
显然,如果我仅执行drop语句,SQL Server数据库将抱怨说新表具有对其他表的外键引用。
我听说过运行以下脚本来找出存在哪些外键,以便我们可以删除它们:
use perls;
SELECT 'ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME +
'] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']'
FROM information_schema.table_constraints
WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' and TABLE_NAME = 'NewTable'
Run Code Online (Sandbox Code Playgroud)
上面给出的结果基本上显示了我需要运行的alter语句。
我需要更自动化的东西。为什么我必须分别删除每个外键约束,然后才能删除表?
我想以一种更简单的方式删除表格。它比我上面要做的要容易。
是的,您必须先删除 FK。我以前遇到过这个问题,并且只编写了自动化该任务所需的脚本。替换下面的 DBName 和 TABLENAME。
警告所有人:此脚本将删除特定表(或表组)以及所有 FK 约束!请谨慎使用,并在执行此类主要操作之前始终进行数据库备份。
use DBName
/*
SCRIPT TO DROP TABLES WITH FK'S, INDEXES
https://mellodev.snipt.net/drop-tables-with-fk-contraints/
*/
set nocount on
declare @tables table (tablename varchar(255));
insert into @tables
select name from sys.tables where name in
('TABLENAME')
-- Iterate tables, drop FK constraints and tables
declare @tablename varchar(255);
declare cTable cursor for
select tablename from @tables
open cTable
fetch next from cTable into @tableName
while @@FETCH_STATUS=0
begin
-- Identify any FK constraints
declare @fkCount int;
SELECT @fkCount = COUNT(*)
FROM sys.foreign_keys
WHERE referenced_object_id = object_id(@tablename)
-- Drop any FK constraints from the table
if (@fkCount>0) begin
declare @dropFkSql nvarchar(max);set @dropFkSql='';
declare @fkName nvarchar(max);
declare cDropFk cursor for
SELECT 'ALTER TABLE [' + OBJECT_NAME(parent_object_id) + '] DROP CONSTRAINT [' + name + ']',name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id(@tablename)
open cDropFk
fetch next from cDropFk into @dropfksql,@fkName
while @@FETCH_STATUS=0
begin
exec sp_executesql @dropFkSql;
select 'Dropped FK Constraint: ' + @fkName
fetch next from cDropFk into @dropfksql,@fkName
end
close cDropFk
deallocate cDropFk
end
-- Drop the table
declare @dropTableSql nvarchar(max);
set @dropTableSql='DROP TABLE [' + @tablename + ']';
exec sp_executesql @dropTableSql;
select 'Dropped table: ' + @tablename
fetch next from cTable into @tableName
end
close cTable
deallocate cTable
Run Code Online (Sandbox Code Playgroud)