1.数据库操作
1)创建数据库: create database database_name
例:create database students
on
( name= students, #逻辑文件名
filename=’f:\data\ students.mdf’,#存放路径及物理文件名
size=3mb, #初始大小
maxsize=unlimited) #最大大小
2)删除数据库: drop datebase database_name;
3)修改数据库字符编码: alter database_name character set utf8;
2.数据表的操作
1)创建表: create table table_name(…….)
Create table Student(
Sno char(7) primary key, --主码
Sname nchar(5) not null, --非空
Sid char(18) unique, --取值唯一
Ssex nchar(1) default ’男’,--默认值为‘男’
Sage tinyint check(Sage>=15 and Sage <=45), --取值范围为15~45
Sdept nvarchar(20) )
Create table SC(
Sno char(7) not null,
Cno char(6) not null,
Grade tinyint,
Primary key (Sno,Cno), --Sno,Cno为主码
Foreign key (Sno) references Student(Sno),--引用Student的外码
Foreign key (Cno) references Course(Cno) )--引用Course的外码
2)删除表: drop table table_name
3) 删除列: alter table table_name drop column col_name
4)添加列: alter table table_name add col_name varchar(20) not null
5)修改列: alter table table_name alter column col_name varchar(50)
6)插入数据:insert into table_name(field1,field2) values(value1,value2)
7)删除数据: delete from table_name where 条件
8)更新数据: update table_name set col1=value1… where 条件
3.约束
1)种类:primary key(主键约束)、default(默认约束)、not null(非空约束)、 unique(唯一约束)、foreign key(外键约束)、check(检查约束)
2)添加约束: alter table table_name add constraint 约束名 约束类型
--添加唯一约束
Alter Table stuInfo Add Constraint UQ_stuID unique(stuID)
--添加默认约束
Alter Table stuInfo
Add Constraint DF_stuAddress default('地址不详') for stuAddress
--添加检查约束
Alter Table stuInfo
Add Constraint CK_stuAge check(stuAge between 15 and 40)
3)删除约束: alter table table_name drop 约束类型 约束名称 注意:删除主键 时,应先删除引用了它的外键
例: alter table student drop foreign key fk_1
4.简单的查询
1)无条件查询: select * from tabel_name
2)条件查询: select *from table_name where 条件
3)排序查询: select col1,col2,…from table_name order by 列 名 desc/asc desc:从大到小排序。asc:从小到大排序 ,默认是asc
4)模糊查询:查询关键字 like 主要使用 % 、’_’、[ ] 三个字符
- “%” 表示匹配0个或多个字符(通配符)
- "_"匹配一个字符
- “[]” 匹配其中的一个(类似正则表达式)
例: 查询学生中姓张的,两个字,三个字的都可以查出来,如:张三、张麻子
select *from student where s_name like '张%'
例: 查询学生中姓张的,且只有两个字