SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software Kodyaz SQL Server and T-SQL Development Tutorials
Development resources, articles, tutorials, samples, codes and tools for .Net, SQL Server, Windows, Windows Phone, SAP and ABAP, like SAP UI5, Screen Personas, etc.




download SQL Server 2016
download SQL Server 2014



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

MS SQL Server Forums









Copyright © 2004 - 2017 Eralper YILMAZ. All rights reserved.
Community Server by Telligent Systems