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 isShotsand 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.ObjectsWe 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.TABLESWe 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.TablesWe 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