views:

66

answers:

1

If you drop a table in SQL Server that has Keys, Indexes, Contraints, etc on it will it drop those as well? I was just wondering when I am building my scripts if I need to create drop scripts for all of those as well or if I can simply drop the tables?

Thanks,

S

+4  A: 

Yes, although you can't drop a table that is referenced by a foreign key in another table.

Here's a procedure for dropping a table with foreign keys that reference it in 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'
Jason Goemaat
Indeed so if you are writing a script to drop everything for instance, you need to do it in such a way that you first drop the tables which reference others.
bjorsig
Yep makes sense thanks gusy
scarpacci
@bjorsig: Unless you have circular references, which in my experience are not common.
Shannon Severance