Home >Database >Mysql Tutorial >How to Create a Table in SQL Server Only If It Doesn't Already Exist?

How to Create a Table in SQL Server Only If It Doesn't Already Exist?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 05:10:45353browse

How to Create a Table in SQL Server Only If It Doesn't Already Exist?

SQL Server Equivalent of MySQL's "CREATE TABLE IF NOT EXISTS"

MySQL's "CREATE TABLE IF NOT EXISTS" syntax creates a table only if it does not already exist. While SQL Server does not support this syntax verbatim, there is an equivalent approach using the "if not exists" clause.

Answer:

To create a table in SQL Server only if it does not exist, use the following syntax:

if not exists (select * from sysobjects where name='TableName' and xtype='U')
create table TableName (
    ColumnName1 dataType1,
    ColumnName2 dataType2,
    ...
)
go

Example:

To create a table called "Cars" if it does not already exist:

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

The above is the detailed content of How to Create a Table in SQL Server Only If It Doesn't Already Exist?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn