EN
MS SQL Server - CREATE TABLE IF NOT EXIST equivalent
0 points
In this article, we would like to show you how to create a table if not exists in MS SQL Server.
Quick solution:
xxxxxxxxxx
1
IF OBJECT_ID(N'[dbo].[table_name]', N'U') IS NULL
2
BEGIN
3
CREATE TABLE [dbo].[table_name] (
4
[column1] DATA_TYPE,
5
[column2] DATA_TYPE,
6
[column3] DATA_TYPE,
7
...
8
);
9
END;
Note:
Go to the official documentation to see available
DATA_TYPES
.
In this example, we create users
table with the following columns and types:
id
- INT IDENTITY(1,1),name
- VARCHAR,role
- VARCHAR.
Query:
xxxxxxxxxx
1
IF OBJECT_ID(N'[dbo].[users]', N'U') IS NULL
2
BEGIN
3
CREATE TABLE [dbo].[users] (
4
[id] INT IDENTITY(1,1),
5
[name] VARCHAR(100) NOT NULL,
6
[role] VARCHAR(15) NOT NULL,
7
PRIMARY KEY ([id])
8
);
9
END;
Database:
