繁体   English   中英

SQL Server删除表

[英]SQL Server Drop Table

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

谢谢,

小号

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM