Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sql server
communitycreator

How to check if a table exists in the SQL server

Shubham Singh Kshatriya

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 is Shots and the name of our database is Edpresso.

1. Using OBJECT_ID()

The OBJECT_ID() function checks if theShots table exists in the database Edpresso database.

USE [Edpresso]
GO
IF OBJECT_ID(N'dbo.Shots', N'U') IS NOT NULL
BEGIN
    PRINT 'Table Exist'
END
An example of OBJECT_ID()

2. Using sys.Objects

We can use sys.Objects to check if the table Shots table exists in the Edpresso database.

USE [Edpresso]
GO
IF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id = OBJECT_ID(N'dbo.Shots') AND Type = N'U')
BEGIN
   PRINT 'Table Exist'
END
An example of sys.Objects

3. Using INFORMATION_SCHEMA.TABLES

We can use INFORMATION_SCHEMA.TABLES to check if the Shots table exists in the Edpresso database.

USE [Edpresso]
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Shots')
BEGIN
    PRINT 'Table Exist'
END
An example of INFORMATION_SCHEMA.TABLES

4. Using sys.Tables

We can use sys.Tables() to check if the Shots table exists in the Edpresso database.

USE [Edpresso]
GO
IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'Shots' AND Type = N'U')
BEGIN
    PRINT 'Table Exist'
END
An example of sys.Tables

RELATED TAGS

sql server
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring