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
Release: 2025-01-04 07:14:35
Original
420 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template