Check If A Table Exists
Check If A Table Exists
Check If A Table Exists
Approach 1: Using
INFORMATION_SCHEMA.TABLES view
We can write a query like below to check if a Customers Table exists in the
current database.
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'Customers')
BEGIN
PRINT 'Table Exists'
END
RESULT:
The above query checks the existence of the Customers table across all the
schemas in the current database. Instead of this if you want to check the
existence of the Table in a specified Schema and the Specified Database then
we can write the above query as below:
IF EXISTS (SELECT *
FROM SqlHintsDemoDB.INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'Customers')
BEGIN
PRINT 'Table Exists'
END
RESULT:
RESULT:
Specifying the Database Name and Schema Name parts for the Table Name is
optional. But specifying Database Name and Schema Name provides an option
to check the existence of the table in the specified database and within a
specified schema, instead of checking in the current database across all the
schemas. The below query shows that even though the current database is
MASTER database, we can check the existence of the Customers table in the
dbo schema in the SqlHintsDemoDB database.
USE MASTER
GO
IF OBJECT_ID(N'SqlHintsDemoDB.dbo.Customers', N'U') IS NOT NULL
BEGIN
PRINT 'Table Exists'
END
RESULT:
Pros: Easy to remember. One other notable point to mention about OBJECT_ID()
function is: it provides an option to check the existence of the Temporary Table
which is created in the current connection context. All other Approaches checks
the existence of the Temporary Table created across all the connections context
instead of just the current connection context. Below query shows how to check
the existence of a Temporary Table using OBJECT_ID() function:
CREATE TABLE #TempTable(ID INT)
GO
IF OBJECT_ID(N'TempDB.dbo.#TempTable', N'U') IS NOT NULL
BEGIN
PRINT 'Table Exists'
END
GO
RESULT:
RESULT
RESULT
catalog view,
sys.Tables is
for the Table
table objects,