SQL Server CREATE TABLE Statement
SQL Server CREATE TABLE Statement
Data Types
1
TP2
Numeric column. Precision –
number of digits, Scale – how many DECIMAL(5,2) → 476.29
Decimal (p,s)
of the digits are located after the DECIMAL(5,2) → 6.29
decimal point
For example:
CREATE TABLE demo_tbl
(
salary DECIMAL(8,2) DEFAULT 9500,
hire_date DATE DEFAULT ’2011-01-27’ ,
birthdate DATE DEFAULT GETDATE()
)
SELECT *
FROM demo_tbl
2
TP2
3
TP2
uniqueness and ensures that no column that is part of the Primary Key can
hold a NULL value. Only one Primary Key can be created for each table.
The syntax for defining a Primary Key Constraint is as follows:
1 column_name column_DataType [DEFAULT value] [CONSTRAINT constraint_name] PRIMARY KEY
For example:
1 CREATE TABLE emps
2 (emp_id decimal(3) CONSTRAINT emps_empid_pk PRIMARY KEY,
3 emp_name varchar(25))
Please note – the square brackets in this demonstration (and in those that
follow) indicate that what enclosed within them is optional, the square
brackets are not part of the CREATE TABLE statement.
For example:
1 CREATE TABLE emps
2 (emp_id decimal(3) CONSTRAINT emps_empid_pk PRIMARY KEY,
3 emp_name varchar(25) CONSTRAINT emps_emnm_nn NOT NULL)
UNIQUE (UQ)
In SQL Server, the Unique constraint requires that every value in a column
(or set of columns) be unique. The syntax for defining a UNIQUE
Constraint is as follows:
1 column_name column_DataType [DEFAULT value] [CONSTRAINT constraint_name] UNIQUE,
For example:
1 CREATE TABLE emps
2 (emp_id decimal(3) CONSTRAINT emps_empid_pk PRIMARY KEY,
3 emp_name varchar(25) CONSTRAINT emps_emnm_nn NOT NULL,
emp_phone varchar(25)CONSTRAINT emps_empn_uq UNIQUE)
4
4
TP2
CHECK (CK)
In SQL Server, the Check constraint defines a condition that each row must
satisfy. The syntax for defining a Check Constraint is as follows:
1 column_name column_DataType [DEFAULT value] [CONSTRAINT constraint_name] CHECK (Cond
Another example:
1 CREATE TABLE emps
2 (emp_id decimal(3) CONSTRAINT emps_empid_pk PRIMARY KEY,
3 emp_name varchar(25) CONSTRAINT emps_emnm_nn NOT NULL,
4 emp_phone varchar(25) CONSTRAINT emps_empn_uq UNIQUE,
emp_mail varchar(25) CONSTRAINT emps_emml_ck CHECK (emp_mail LIKE '_%@%.%'),
5 emp_sal decimal(8,2) CONSTRAINT emp_sal_ck CHECK (emp_sal <&a
6
Example:
The Parent Table
1 CREATE TABLE deps
5
TP2
For example
6
TP2