SQL Server administration and T-SQL development, Web Programming with ASP.NET and Javascript, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software Kodyaz Development Resources
Development resources, articles, tutorials, samples, codes and tools for .Net, SQL Server, Vista, etc.




How to use SQL DROP Table If Table Exists in SQL Database


If you want to drop a table which might have already created in the SQL database, you can use sql DROP TABLE command. The sql drop table command will run successfully if sql table table exists. Contrarily if the sql table does not exist in SQL Server database, then sql DROP TABLE command will cause sql engine to throw the following error.

Msg 3701, Level 11, State 5, Line 1
Cannot drop the table 'Sample SQL Table', because it does not exist or you do not have permission.

In order to modify sql script to drop existing sql tables, sql developers can use conditional DROP statements. It is as simple as adding an tsql IF clause before executing the sql DROP TABLE command.





Here is a sample sql code to drop existing table

Create Table [Sample SQL Table] (id_column int);

if exists (
  select * from sys.tables where name = N'Sample SQL Table'
)
  drop table [Sample SQL Table]

An here is an other sql codes that can be used to check if sql table exists already in the SQL Server database, and if exists dropping sql table.
If sql table is not existing then the t-sql DROP Table command will not be executed.

Create Table [Sample SQL Table] (id_column int);

if OBJECT_ID(N'Sample SQL Table',N'U') IS NOT NULL
  drop table [Sample SQL Table]

SQL developers can use one version of the above two sample sql codes to drop tables in sql databases.







Related SQL Resources

SQL Server Articles

SQL Server 2012

SQL Server Tools

SQL Blog

SQL Server 2008 Blog

Certification Exams Blog

Reporting Services Blog

Analysis Services Blog

MS SQL Server Forums



Free Exam Vouchers









Copyright © 2004 - 2012 Eralper Yilmaz. All rights reserved.
Community Server, by Telligent Systems