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

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

Barbara Streisand
Barbara StreisandOriginal
2025-01-04 07:14:35414browse

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

Equivalent of CREATE TABLE IF NOT EXISTS in SQL Server

The MySQL command CREATE TABLE IF NOT EXISTS is used to create a table only if it does not already exist. This syntax is not directly compatible with SQL Server.

Alternative Syntax in SQL Server

To achieve the same functionality in SQL Server, an alternative syntax using a conditional query can be employed:

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

In this code:

  • select * from sysobjects where name='cars' and xtype='U' checks if a table named 'cars' already exists.
  • if not exists evaluates the result of the query and executes the create table statement only if the table does not exist.

Additional Notes

  • In SQL Server, table names are case-insensitive.
  • The go statement is used to terminate a batch of Transact-SQL (T-SQL) statements.

The above is the detailed content of How to Create a Table Only if It Doesn't Exist in SQL Server?. 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