表的创建
creat 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,
--部门描述
DepartmentRemark text
)
create table [Rank]
(--职级编号,primary key:主键,identity(1,1):自动增长<初始值1,增长步长1
RankId int primary key identity(1,1),
--职级名称
RankName nvarchar(50) not null,
--职级描述
RankRemark text
)
--员工
create table People
(
PeopleId int primary key identity(1,1),--员工编号
DepartmentId int references Department(DepartmentId)not null,--部门(引用外码)
RankId int references Department(DepartmentId)not null,--职级(引用外码)
PeopleName nvarchar(50) not null,--姓名
PeopleSex nvarchar(1) default('女')check(PeopleSex='男'or PeopleSex='女'),--性别
PeopleBirth smalldatetime not null,--生日
PeopleSalary decimal(12,2)check(PeopleSalary>=1000 and PeopleSalary<=1000000)not null,--月薪,(总长度,小数点后位数)
PeoplePhone varchar(20)unique not null,--电话,unique唯一约束
PeopleAddress varchar(300),--地址
PeopleAddTime smalldatetime default(getdate()) --添加时间
)
SQL中的一些数据类
–char:定长,char(10),无论存储的数据是否真的到了10个字节,它都要占用10个字节.
–char(10)存储’a,b’,仍然占用10个字节.
–varchar:变长,varchar(10)表示最多占用10个字节.
–varchar(10)存储’ab’,占用2个字节.
–text:长文本
–char,varchar,text前面加n:存储unicode字符,对中文友好.
–varchar(100):存储100个字母或者50个汉字
–nvarchar(100):存储100个字母或者100个汉字