161

I am writing a Stored procedure in SQL Server 2008. I need to check if a table exists in the database. If it doesn't then I need to create it.

How do I do this?

2
  • 2
    Related, if not duplicate: Check if table exists in SQL Server.
    – user456814
    Commented Oct 21, 2015 at 10:03
  • 1
    This is a great question that everyone working with SQL Server will ask eventually. It's sad that SQL Server doesn't have the friendly Oracle style CREATE OR REPLACE
    – Davos
    Commented Nov 20, 2015 at 2:26

10 Answers 10

178

Something like this

IF  NOT EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))

BEGIN
CREATE TABLE [dbo].[YourTable](
    ....
    ....
    ....
) 

END
2
  • 3
    respectfully consider a few changes (for the sake of the execution plan) using an indexed field instead of * (object_id is the numeric field commonly refered to in this table) use type = 'U' instead of type in (N'U') (the column _type is of type char using Nchar causes an implicit conversion which often causes issues with the cardinality estimator) if (not exists (select object_id from sys.objects where object_id = OBJECT_ID(N'[dbo].[client_tgi_g67_period_list]') and type = 'U')) Commented Apr 29, 2019 at 18:46
  • Is the second space between IF and NOT intentional? Commented Feb 15, 2021 at 14:16
172

Just for contrast, I like using the object_id function as shown below. It's a bit easier to read, and you don't have to worry about sys.objects vs. sysobjects vs. sys.all_objects vs. sys.tables. Basic form:

IF object_id('MyTable') is not null
    PRINT 'Present!'
ELSE
    PRINT 'Not accounted for'

Of course this will show as "Present" if there is any object present with that name. If you want to check just tables, you'd need:

IF object_id('MyTable', 'U') is not null
    PRINT 'Present!'
ELSE
    PRINT 'Not accounted for'

It works for temp tables as well:

IF object_id('tempdb.dbo.#MyTable') is not null
    PRINT 'Present!'
ELSE
    PRINT 'Not accounted for'
1
  • 4
    I usually see the other method used (checking the sys tables) but this seems ore legible and compact. is there any reason not to prefer this method over the accepted answer? (Such as compatibility issues with SQL migration to different DB providers, speed, etc)?
    – user677526
    Commented Jul 7, 2014 at 13:36
30

Let us create a sample database with a table by the below script:

CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE dbo.tblTest (Id INT, Name NVARCHAR(50))

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a tblTest Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

The above query checks the existence of the tblTest 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 Test.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = N'dbo'  AND TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

Pros of this Approach: INFORMATION_SCHEMA views are portable across different RDBMS systems, so porting to different RDBMS doesn’t require any change.

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a tblTest Table exists in the current database.

IF OBJECT_ID(N'dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

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 tblTest table in the dbo schema in the Test database.

USE MASTER
GO
IF OBJECT_ID(N'Test.dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

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

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.tblTest') AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'tblTest' AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Sys.Tables catalog view inherits the rows from the Sys.Objects catalog view, Sys.objects catalog view is referred to as base view where as sys.Tables is referred to as derived view. Sys.Tables will return the rows only for the Table objects whereas Sys.Object view apart from returning the rows for table objects, it returns rows for the objects like: stored procedure, views etc.

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per [Microsoft BOL][1] link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'tblTest' AND xtype = N'U')
BEGIN
  PRINT 'Table Exists'
END

Reference: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

2
  • Important to note that this answer provides which approach needs the database to be specified and which do not. This is extremely valuable and for scripts that run to setup and update an operational database when there are multiple of the same database running on the same instance, this is the key! Great information. Commented Dec 29, 2017 at 16:43
  • 1
    Upped as an excellent answer. This should be the accepted answer. I used INFORMATION_SCHEMA.TABLES and specified the name and schema values in my WHERE clause. Thanks.
    – whytheq
    Commented Dec 14, 2022 at 10:37
12

EDITED

You can look into sys.tables for checking existence desired table:

IF  NOT EXISTS (SELECT * FROM sys.tables
WHERE name = N'YourTable' AND type = 'U')

BEGIN
CREATE TABLE [SchemaName].[YourTable](
    ....
    ....
    ....
) 

END
0
4
Declare @Username varchar(20)
Set @Username = 'Mike'

if not exists 
(Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')

Begin
    Create table tblEmp (ID int primary key, Name varchar(50))
    Print (@Username + ' Table created successfully')
End

Else

Begin
    Print (@Username + ' : this Table Already exists in the database')
End
1
  • 4
    Welcome to StackOverflow. When answering questions, consider adding an explanation too. Code alone isn't very helpful most of the time.
    – Viktor
    Commented Aug 23, 2019 at 7:43
3
IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE  TABLE_NAME = 'd020915'))
BEGIN
  declare @result int
  set @result=1
  select @result as result
END
0

Try the following statement to check for existence of a table in the database:

If not exists (select name from sysobjects where name = 'tablename')

You may create the table inside the if block.

1
  • 3
    While that syntax will work, sysobjects is a compatibility view that exists only to avoid breaking older code. My suggestion would be to use system catalog views (e.g. sys.objects, sys.tables) for code that will only target SQL Server 2008 instances, and information schema views (e.g. information_schema.tables) for code that needs to be portable. You can find more information on the different views here: Querying the SQL Server System Catalog
    – ajk
    Commented May 10, 2011 at 15:44
0

Something like this :

if not exists (select Top 1 name from sys.all_objects obj 
                   where obj.schema_id=schema_id() and obj.object_id=object_id(N'[dbo].[TestTable]') and obj.type in (N'U') )
    
    BEGIN
      CREATE TABLE [dbo].[TestTable]
      (
        [Id] [bigint] IDENTITY (1,1) NOT NULL,  
        [Name] [nvarchar](20) NULL,
        CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
        (
          [Id] ASC    
        ) ON [PRIMARY]
      ) ON [PRIMARY]
    END
1
  • 1
    Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community? Commented Nov 23, 2023 at 22:55
0

You don't need to programmatically solve this or query the database as to whether a schema exists. Use this instead:

create table if not exists mytable(...)
1
  • Are you sure this syntax will work on MS SQL server? Commented Aug 27 at 12:26
-2

If I am not wrong, this should work:

    if not exists (Select 1 from tableName)
create table ...
2
  • 4
    what if the table exists but is empty,,this will be true in that case
    – SQLMenace
    Commented May 10, 2011 at 14:58
  • @SQLMeance Oh ok, I understand from your answer that you are checking for the type 'U' in sys.objects, Could you help me understand, why you recommend this? and can a table exist anywhere else ? Thank you in advance
    – RaM
    Commented May 10, 2011 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.