SQL Server删除表

问题描述:

如果您在SQL Server中删除了一个包含Keys,Indexes,Contraints等的表,它是否也会删除这些表?我只是想知道,如果我需要为所有这些创建删除脚本,或者如果我可以简单地删除这些表,我何时构建脚本?SQL Server删除表

感谢,

小号

是的,虽然你不能删除由另一个表的外键引用的表。

这里有一个程序丢弃与引用它的SQL Server 2008中的外键的表:

create table TA (AID int identity(1, 1), OtherId int, Name varchar(512), constraint PK_TA primary key (AID)) 
create table TB (BID int identity(1, 1), OtherId int, Name varchar(512), constraint PK_TB primary key (BID)) 
alter table TA add constraint FK_TA_TB foreign key (OtherId) references TB (BID) 
alter table TB add constraint FK_TB_TA foreign key (OtherId) references TA (AID) 

drop table ta -- doesn't work 
drop table tb -- doesn't work 

create procedure my_DropTable @tableName varchar(512) as 
begin 
    if OBJECT_ID(@tableName) is null begin print 'OBJECT DOES NOT EXIST' return end 
    declare @sql nvarchar(max) 
    while exists (select * from sys.foreign_keys where referenced_object_id = object_id(@tableName)) 
    begin 
     select @sql = 'ALTER TABLE ' + OBJECT_NAME(parent_object_id) + ' DROP CONSTRAINT ' + OBJECT_NAME(object_id) 
     from sys.foreign_keys where referenced_object_id = object_id(@tableName) 

     exec sp_executesql @sql 
    end 
    set @sql = 'DROP TABLE ' + @tableName 
    exec sp_executesql @sql 
end 

exec my_DropTable 'TA' 
exec my_DropTable 'TB' 
+0

的确如此,如果你正在编写一个脚本,例如放下一切,你需要做的是在这样的你首先删除引用其他表格的方法。 – bjorsig 2010-09-09 22:07:45

+0

是的,感谢gusy – scarpacci 2010-09-09 22:09:18

+0

@bjorsig:除非你有循环引用,这在我的经验并不常见。 – 2010-09-10 00:28:20