CREATE TABLE IF NOT EXISTS equivalent in SQL Server

How to use CREATE TABLE IF NOT EXISTS in SQL Server which does not provide a complete user-friendly way for testing table existence.

By Tim Trott | SQL and mySql Tutorials | May 1, 2011

MySql contains a very useful table construct element which checks that the table does not exist before creating it. MySql's create table if not exist construct will do as it says, it will create the table if it does not exist.

sql
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    [table_options]
    [partition_options]

Microsoft SQL Server lacks the function of create table if not exists, meaning table creation queries will fail if the table already exists. You could drop the table before creating it, but again, you may run into problems if the table does not exist.

This function can be used to test if the table exists and, if it does not exist, create it.

sql
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='tbl_name' and xtype='U')
    CREATE TABLE tbl_name (
        Name varchar(64) not null
    )
GO

It is nowhere near as elegant as the MySql version CREATE TABLE IF NOT EXISTS, but it functions in the same way.

Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 5 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. GR

    On Friday 21st of February 2020, greg said

    This would be a bit more elegant:
    IF OBJECT_ID('dbo.tbl_name', 'U') IS NULL CREATE TABLE dbo.tbl_name (VARCHAR(64));

    1. VI

      On Sunday 12th of April 2020, vij replied

      what is dbo and U

      1. BE

        On Friday 3rd of July 2020, Benjaa replied

        dbo is the default schema (you need to change it if the table is in another schema), U is the object ID type for Table.

    2. MA

      On Friday 28th of February 2020, mark replied

      Thanks for the tip Greg. Worked great for me!

  2. JA

    On Friday 6th of December 2019, Jack said

    Thank you very much Tim!
    You saved me some time figuring it out.
    I would like to know why did they chose not support a function for it.