DROP TABLE IF EXIST in MS SQL

MS SQL equivalent to DROP TABLE IF EXIST

When developing an application using MySQL I generally use this syntax:


DROP TABLE IF EXISTS [table_name];
CREATE TABLE [table_name] ( Columns declaration here )

This sql script is useful when I’m about to clear out the data in a table. However in Microsoft SQL (MS SQL) this method will not work.
After I do some searching, I come up with this syntax:


IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[table_name]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[table_name];
CREATE TABLE [dbo].[table_name] ( Columns declaration here );

The above sql script will be equivalent to MySQL syntax before. Hope this will be helpful 🙂

Advertisements

2 thoughts on “DROP TABLE IF EXIST in MS SQL

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s