Wednesday, 1 April 2015

How to Check and Delete if a Table or Database already exists in SQL Server

SQL Query to Check and Delete if a Table or Database already exists in SQL Server
Use caution when dropping tables. Once you drop a table, you will not be able to get it back unless you restore a backup.
'Checking the Table Existence , If yes Dropping it.
'Here it checks the Table Name from all the Schemas.
IF EXISTS ( SELECT NAME from SYS.TABLES where NAME ='EMPLOYEE')
DROP TABLE EMPLOYEE
GO

'Creating the Table again after Dropping.
Create Table EMPLOYEE (
EID INT,
EMPNAME VARCHAR(25)
DEPT VARCHAR(25),
DOJ DATE
SAL DECIMAL (10,2)
)
GO 

'Checking the Database Existence , If yes Dropping it.

IF EXISTS ( SELECT [Name] From SYS.DATABASES Where [Name] = 'TAMATAM' ) 
DROP DATABASE TAMATAM
GO 

'Creating the Database again after Dropping.
CREATE DATABASE TAMATAM
GO

No comments:

Post a Comment

Follow Me by Email

ExcelKingdom-Popular Posts

ExcelKingdom-Random Posts