建立dept和emp表,并用dept表中的dept_id设置为emp表的外键
create table dept
(
dept_name nvarchar(20) not null,
dept_address nchar(20),
dept_id int constraint PK_dept primary key --dept表的主键,命名为PK_dept
)
create table emp
(
emp_name nvarchar(20) not null,
emp_sex nchar(1),
emp_age int,
emp_id int constraint PK_emp primary key, --emp表的主键
dept_id int constraint FK_emp_dept foreign key references dept(dept_id) --外键
)
插入和约束:
create table student
(
stu_id int constraint PK_stu primary key,
stu_name nvarchar(20) unique not null, --unique约束,stu_name的值不能重复
stu_sex nvarchar(1) not null default('男'), --stu_sex的默认值为:男
stu_sal int check (stu_sal>=1000 and stu_sal<=8000) --check约束,stu_sal的值只能在1000到8000之间
)
insert into student(stu_id,stu_name,stu_sal) values(1,'张三',6000); --没有给stu_sex赋值,默认为男
insert into student values(2,'李四','男',7000);
insert into student values(3,'小娟','女',5000);
得出的结果: