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 TrottSQL and mySql Tutorials • May 1, 2011
CREATE TABLE IF NOT EXISTS equivalent in SQL Server

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.

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. 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 comments. Why not join the discussion!

New comments for this post are currently closed.