--切换数据库
use DBTEST
--创建表基本语法
--create table 表名
--(
-- 字段名1 数据类型,
-- 字段名2 数据类型
--)
--判断表是否存在
if exists(select * from sys.objects where name='Department' and type='U')
drop table Department
--建表(部门,职级,员工)
create table Department
(
--部门编号,primary key,主键
--identity(1,1): 自动增长,初始值为1,增长步长为1
DepartmentId int primary key identity(1,1),
--部门名称
DepartmentName nvarchar(50) not null,
--部门描述(不好确定字数的类型用text)
DepartmentRemark text
)
--char:定长,char(10),无论存储数据是否真的到了10个字节,都要占10个字节
--char(10)存储'ab',仍然占用10个字节
--varchar:变长,varchar(10),最多占用10个字节
--varchar(10)存储''ab',占用2个字节
--text:长文本,效率低
--char,varchar,text前面加n:存储unicode字符,对中文友好
--varchar(100):存储100个字母或者50个汉字
--nvarchar(100):存储100个字母或者100个汉字
--建表
--因为rank是特殊字符,所以需要加上中括号
create table [Rank]
(
--职级编号,primary key,主键
--identity(1,1): 自动增长,初始值为1,增长步长为1
RankId int primary key identity(1,1),
--职级名称
RankName nvarchar(50) not null,
--职级描述(不好确定字数的类型用text)
RankRemark text
)
--员工
create table People
(
PeopleId int primary key identity(1,1),--员工编号
--通过部门表的主键,可以得知该职工的所有信息
--references:外键,自动从关联表中检查是否有该编号,若有,则可添加,若没有,则会添加失败,为了防止将没有的部门编号或者职级编号输入进来
DepartmentId int references Department(DepartmentId) not null,--部门(引用外键)
RankId int references [Rank](RankId) not null, --职级
PeopleName nvarchar(50) not null,--姓名
--default('男'):默认值是男
--为了防止乱填,添加约束,要么男要么女
PeopleSex nvarchar(1) default('男') check(PeopleSex='男' or PeopleSex='女') not null,--性别
--date:存储年月日,以前的版本可能没有date,所以一般比较喜欢用下面的
--datetime:时分秒
--smalldatetime:比datetime范围小,空间小,效率高,一般用这个
PeopleBirth smalldatetime not null,--生日
--12:总长度为12,2:小数点后两位
PeopleSalary decimal(12,2)check(PeopleSalary>=1000 and PeopleSalary<=1000000) not null,--月薪
--unique 唯一
PeoplePhone varchar(20) unique not null,--电话
PeopleAddress varchar(300),--地址
PeopleAddTime smalldatetime default(getdate()) --添加时间
)