SQL---基本
2017/7/25.修订————基本的添加约束、增删改查数据表和列
1 create database Stu 2 go--新建数据库 3 4 use Stu 5 go--使用数据库 6 7 create table db_stuInfo 8 ( 9 --创建表约束 10 Id int identity(1,1), --primary key,--Identity 11 Name varchar(50), --not null 12 Num int , --unique 13 Age int, --check(Age>=18 and Age<=65) 14 Sex char(2), --default('男') 15 Born date, 16 Class varchar(50) , --references db_stuInfo(Class)(在关联列表中添加,本列表为主键列表) 17 AddTime datetime --default(getdate()) 18 ) 19 go--新建表 20 21 22 23 /*创建表时添加约束规则: 24 25 --创建表约束-- 26 27 --主键约束 primary key 唯一,不为空,不重复 28 --唯一约束 unique 唯一,及非主键约束,限定字段值存在一数据的唯一性 29 --检查约束 check(表达式) 设置规则,进行判断 30 --默认约束 default(value) 设置默认值 31 --外键约束 references 主键表 (主键表列字段) 与主键表字段关联 32 --非空约束 Not null 必填,不为空 33 34 --添加表约束-- 35 36 Alter table 数据表 37 ADD constraint 约束名 约束类型 具体的约束说明 38 39 */ 40 --PS: 41 Alter table db_stuInfo 42 Add constraint PK_StuId primary key(Id) 43 go--添加主键约束 44 Alter table db_stuInfo 45 Add constraint UQ_StuNum unique(Num) 46 go--添加唯一约束 47 Alter table db_stuInfo 48 Add constraint CK_StuAge check(Age>=18 and Age<=65) 49 go--添加检查约束 50 Alter table db_stuInfo 51 Add constraint DF_StuAddTime default(getdate()) for AddTime 52 go--添加默认约束 53 Alter table db_stuClass 54 Add constraint FK_StuClass foreign key(Class) references db_stuInfo(Class) 55 go--添加外键约束 56 Alter table db_stuInfo 57 alter column Sex char(2) not null 58 go--添加非空约束 59 60 61 62 63 insert into db_stuInfo(Name,Num,Age,Sex,Born,Class,AddTime) values('Xn',170801,22,'女','2000-10-10','DN1708',GETDATE()) 64 go--插入数据记录 65 insert into db_stuInfo values('Tt',null,null,'男',null,null,getdate())--插入数据记录简写 66 go--PS:添加过标识列无需添加values;在添加值时(null!=''(字符串空)),在''中表示值为空字符串,null表示值为空 67 alter table db_stuInfo 68 add ClassGuide varchar(50) 69 go--添加列字段 70 71 EXEC sp_rename 'db_stuInfo.num', 'Num', 'column' 72 go--修改字段列(此方法通过存储过程实现) 73 update db_stuInfo set Age='男' 74 go--更新数据记录(set后检索的所有更改) 75 update db_stuInfo set Born='2001-11-11' where Id=1 76 go--更新数据记录,添加条件(更改where约束的字段) 77 78 select * from db_stuInfo 79 go--查询数据表 80 select * from db_stuInfo where Name='zm' 81 go--查询指定列中的指定数据 82 select Id,Name,Class from db_stuInfo 83 go--查询指定列 84 select Id as'编号',Name as'姓名',Age as'年龄',Born as'出生',Class as'班级',AddTime as'添加时间' from db_stuInfo 85 go--查询数据表并添加字符标示显示 86 87 88 use master 89 go--使用其他数据库 90 drop database Stu 91 go--删除数据库(先跳转使用其他数据库,才可删除当前使用中的数据库) 92 93 drop table db_stuInfo 94 go--删除数据表
Miss you, escape from you!
(想你,从逃避你开始!)