Before we create a new table or perform some CRUD operations on a table, it is important to check if it exists in the database.
In this shot, we discuss a few approaches to check if a particular table exists in the SQL Server.
For the entire shot, we will assume that the name of our table isShots
and the name of our database isEdpresso
.
OBJECT_ID()
The OBJECT_ID()
function checks if theShots
table exists in the database Edpresso
database.
USE [Edpresso]GOIF OBJECT_ID(N'dbo.Shots', N'U') IS NOT NULLBEGINPRINT 'Table Exist'END
sys.Objects
We can use sys.Objects
to check if the table Shots
table exists in the Edpresso
database.
USE [Edpresso]GOIF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id = OBJECT_ID(N'dbo.Shots') AND Type = N'U')BEGINPRINT 'Table Exist'END
INFORMATION_SCHEMA.TABLES
We can use INFORMATION_SCHEMA.TABLES
to check if the Shots
table exists in the Edpresso
database.
USE [Edpresso]GOIF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Shots')BEGINPRINT 'Table Exist'END
sys.Tables
We can use sys.Tables()
to check if the Shots
table exists in the Edpresso
database.
USE [Edpresso]GOIF EXISTS(SELECT 1 FROM sys.Tables WHERE Name = N'Shots' AND Type = N'U')BEGINPRINT 'Table Exist'END