CREATE TABLE command in SQL Server

In SQL Server (Transact-SQL), the CREATE TABLE statement is used to create and define tables.

In SQL Server (Transact-SQL), the CREATE TABLE statement is used to create and define tables.

Syntax CREATE TABLE command in SQL Server

 CREATE TA BLE ten_bang 
(
cot1 kieu_du_lieu [ NULL | NOT NULL ],
cot2 kieu_du_lieu [ NULL | NOT NULL ],

);

Variable name or variable value

ten_bang

The name of the table you want to create.

cot1, cot2

The column you want to create in the table. Each column has 1 data type. The column must be defined as NULL or NOT NULL, if left blank, the database will default to NULL.

For example

 CREATE TABLE nh anvien 
( nhanvien_id INT NOT NULL,
ho VARCHAR(50) NOT NULL,
ten VARCHAR(50),
luong MONEY
);

The CREATE TABLE command above will create a table named nhanvien with 4 columns:

  1. The nhanvien_id column (employee ID) has an INT data type and does not contain a NULL value.
  2. The second column is ho (employee family) of VARCHAR data type (maximum 50 characters) and does not contain NULL value.
  3. The third column is the ten (employee name) of the VARCHAR data type (up to 50 characters) and can contain NULL values.
  4. The fourth column is luong (employee salary) with MONEY data type and can contain NULL values.

The only problem with this CREATE TABLE statement is that the primary key has not been defined for the table. It is possible to edit a bit and define it as the primary key as follows.

 CREATE TABL E nhanvien 
( nhanvien_id INT PRIMARY KEY,
ho VARCHAR(50) NOT NULL,
ten VARCHAR(50),
luong MONEY
);

By using the keyword PRIMARY KEY after the nhanvien_id field, SQL Server will retrieve the username as the primary key for the table.

Previous article: Data types in SQL Server

Lesson: Main key PRIMARY KEY in SQL Server

5 ★ | 1 Vote