Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Drop Table

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

like image 512
scarpacci Avatar asked Feb 26 '23 06:02

scarpacci


1 Answers

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'
like image 165
Jason Goemaat Avatar answered Mar 06 '23 08:03

Jason Goemaat