265

CREATE TABLE IF NOT EXISTS works on mysql but fails with SQL Server 2008 R2. What is the equivalent syntax?

10
  • 1
    justcheckingonall.wordpress.com/2008/03/01/… Commented Jun 29, 2011 at 13:00
  • 14
    Actually this is not a duplicate of the marked question. This question is asking how to create if it does not exists. because we need a GO after create, we cannot put the create command inside BEGIN and END block, as the answer for other question suggests. Commented Oct 23, 2014 at 7:00
  • 2
    @JNK, when you where marking this question as basic, your link might have been on top of the search results. however on this date, this question is on top of Google search. Commented Oct 23, 2014 at 7:02
  • @Bistro it doesn't matter at all which question is higher ranked in google results. It matters which came first. This Q can still point to the original. Commented Oct 23, 2014 at 12:08
  • 5
    This was closed as a duplicate of a different question. The logic behind it being closed is like the XY problem in reverse. You’re telling the asker that they should have asked Y when they’re actually asking X (whereas in the XY problem the asker asks Y when they’re trying to solve X). I.e., the asker did the right thing and the question is closed? sad face Commented Jun 12, 2018 at 22:44

1 Answer 1

282
if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Sign up to request clarification or add additional context in comments.

4 Comments

Better yet - use the specific sys.tables catalog view instead of having to remember what obscure xtype a table is...
@marc_s: Yes. Another good way :o) In fact, probably a better way.
Since this is the top question for this topic in Google even though it has been closed: if not exists (select * from sys.tables t join sys.schemas s on (t.schema_id = s.schema_id) where s.name = 'myschema' and t.name = 'cars') create table myschema.cars ( Name varchar(64) not null )
Coming back to this in 2017: IF OBJECT_ID(N'dbo.Cars', N'U') IS NULL BEGIN CREATE TABLE dbo.Cars (Name varchar(64) not null); END;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.