一. 对表进行操作
--使用 create table 语句创建表
create table 表名(字段 数据类型 约束)
create table Student(
StudenName varchar(50) --学生姓名
————————————————
--使用 drop table 删除表
--注意事项:删除表时,如果有主外建关系,必须先主表,在删除从表
drop table 表名 --删除一个表
drop table Student
drop table 表名,表名... --删除多个表
drop table Result,Student
1.3 修改表
--注意事项: []中括号中的内容可以不写
1.添加字段
alter table 表名
add 字段名 数据类型 [约束(非空)]
alter table Student
add Sex char(2) not null --修改字段的数据类型和非空约束
2.添加约束
alter table 表名
add constraint 约束命名 约束类型(约束内容)
alter table Student
add constraint PK_Student_id primary key(Id) --添加主键约束
3.删除约束
alter table 表名
drop constraint 约束名
alter table Student
drop constraint PK_Student_id --删除主键约束
4.删除列
alter table 表名
drop column 列名
alter table Student
drop column StudentId --删除 StudentId列
5.修改列
alter table 表名
alter column 列名 数据类型
咧如:
alter column StudentId nvarchar(50) --修改 StudentId列数据类型为 nvarchar(50)
1.4 添加约束
--创建时 create
2. 检查约束 check(具体条件) --最好在修改时添加 可以自己起名字 删除时方便
4. 唯一约束 unique --最好在修改时添加 可以自己起名字 删除时方便
6. 非空 not null --最好创建时添加上
7. 标识列 identity(种子,增值) --最好创建时添加上
--修改时 alter
1. 主键约束 constraint primary key(具体字段)
3. 默认约束 constraint default ('文本、日期' 数字) for 列名
5. 外键约束 constraint foreign key(字段) references 表名(字段)
--约束命名规范
2. 检查约束 CK_表名_列名
4. 唯一约束 UQ_表名_列名
* 注意事项: 1.日期类型需要单引号括起来,数字类型不需要
* 3.修改时添加约束,可以自定义名字
* 5.如果创建时没添加非空约束,可以通过 alter column 列名 数据类型 非空(约束) 修改
*/
--创建时添加约束
create table 表名(
字段 数据类型 约束,
...
)
create table Student(
StudentNo int primary key, --学生编号 主键约束
LoginPwd varchar(255) check(len(LoginPwd)>=6) --密码 检查约束
Subject int foreign key references Subject(id) --科目 外键约束
Address varchar(255) default('学生宿舍') --现住址 默认值约束
--修改时添加约束
alter table 表名
constraint 约束命名 约束类型(约束内容),
)
alter table Student
constraint CK_Student_Pwd check(len(LoginPwd)>=6), --密码 检查约束
constraint DF_Student_Address default('学生宿舍') for Address, --现住址 默认值约束
版权声明:本文为CSDN博主「自学之路←_←」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
