SQL Server删除表

时间:2010-09-09 22:02:12

标签: sql sql-server tsql sql-server-2008

如果你在SQL Server中删除了一个包含键,索引,约束等的表,那么它也会删除它们吗?我只是想知道我何时构建我的脚本,如果我还需要为所有这些脚本创建drop脚本,或者我可以简单地删除表格?

谢谢,

取值

1 个答案:

答案 0 :(得分:8)

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

这是一个删除带有在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'