Languages
[Edit]
EN

MS SQL Server - CREATE TABLE IF NOT EXIST equivalent

0 points
Created by:
Rubi-Reyna
677

In this article, we would like to show you how to create a table if not exists in MS SQL Server.

Quick solution:

IF OBJECT_ID(N'[dbo].[table_name]', N'U') IS NULL 
BEGIN   
	CREATE TABLE [dbo].[table_name] (
        [column1] DATA_TYPE,
        [column2] DATA_TYPE,
        [column3] DATA_TYPE,
        ...
    );
END;

Note:

Go to the official documentation to see available DATA_TYPES.

Practical example

In this example, we create users table with the following columns and types:

  • id - INT IDENTITY(1,1),
  • name - VARCHAR,
  • role - VARCHAR. 

Query:

IF OBJECT_ID(N'[dbo].[users]', N'U') IS NULL 
BEGIN   
	CREATE TABLE [dbo].[users] (
        [id] INT IDENTITY(1,1),
        [name] VARCHAR(100) NOT NULL,
        [role] VARCHAR(15) NOT NULL,
        PRIMARY KEY ([id])
    );
END;

Database:

Table columns created by SQL CREATE TABLE - HeidiSQL preview
Table columns created by SQL CREATE TABLE - HeidiSQL

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MS SQL Server - problems

MS SQL Server - CREATE TABLE IF NOT EXIST equivalent
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join