Check wheather a Table Exists in Database or Not in SQL
Whenever you create a new table in a Database you have to check wheather with same name any table
exist or not
So there are two ways to check wheather a table exists in Database or Not
Script 1
IF OBJECT_ID('dbo.Employee', 'U') IS NOT NULL DROP TABLE dbo.Employee;
Create Table dbo.Employee (Empid int,Empname nvarchar(50))
The first statement will check wheather any object ie table exist with this name or not if exist
it will drop the table and create a new table else it will directly create a new table
Script 2
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA ='dbo.'
AND TABLE_NAME='Employee')
DROP TABLE dbo.Employee;
Create Table dbo.Employee (Empid int,Empname nvarchar(50))
Or to check only the table exist or not in the Database
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA ='dbo.'
AND TABLE_NAME='Employee'
Note: It's always a good practise whenever you create a new table in a database check wheather the table exist or not in a Database Always create a table using Script 1.
No comments:
Post a Comment