如果您在SQL Server中删除一个有键、索引、约束等的表,它会将这些也一并删除吗?我只是想知道当我编写脚本时是否需要为所有这些创建删除脚本,还是只需删除表格即可?
谢谢,
S
谢谢,
S
是的,虽然你不能删除被其他表外键引用的表。
以下是在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'