Friday, April 26, 2013

SQL SERVER DROP TABLE

SQL SERVER DROP TABLE.

                              SQL Server Drop Table , drops the table from the database. ie dropping data+structure of the table.
This operation is permanent, ie Once table is dropped, user cannot get it back.

SYNTAX:
              Drop table [dbname].[schema].[tablename];


For ex:   Drop table customers
           drop table  [dbo].[customers]

   uses current database.

Note: if ur table is not associated with any schema. then [dbo]
 is default schema. u can ignore this also.
simply   drop table [tablename]

Drop table customer associated with profile schema.

drop table [profile].[customer].

uses current database.

Check before dropping a table using Object_ID

if (OBJECT_ID(N'sports','U') is not null)
begin
            print 'sports table exists and dropping' 
            drop table sports;
end

Object_ID tables 2 arguments 
                    1.table name
                     2.type in this case User Defined table , so 'U'

Drop table which has spaces in table name.i.e "order details"

Drop table [order details];


Drop table which has square brackets in it. i.e '[customer]'

 drop table [[customer]]]

 

 DROP Table which has Foreign and Primary Key relationships.

1.First drop all child tables.
2.Second drop parent table.


otherwise Exception will be thrown "Msg 3726, Level 16, State 1, Line 12
Could not drop object 'tablename' because it is referenced by a FOREIGN KEY constraint."
 for ex: drop table [child table1],[child table2],....[parent table]

DROP MULTIPLE TABLE


Drop table  [table1],[table2] ....

TAGS: SQL SERVER DROP TABLE, SQL SERVER DROP TABLE SYNTAX, DROP Multiple tables in SQL SERVER, DROP Parent child tables in SQL SERVER.

No comments:

Post a Comment