创建(create):
创建一个Student学生表,Id 作为一个不可为空的主键,且自动增长;StudentName 学生姓名不可为空;Age 学生年龄不可为空,且默认值为18;Birthday 学生出生日不可为空,且默认值为当前时间。
create table Student(
Id int not null primary key identity(1,1),
StudentName varchar(20) not null,
Age int not null default(18) ,
Birthday datetime not null default(getdate())
)
效果图:
增加(insert):
--插入一条
insert into Student (StudentName,Age) values ('李白',20)
--插入多条
--假设有一个NewStudent新生表,该表有Id和NewName字段,那么就可以把该表里所有学生的名字添加到Student表里
insert into NewStudent(NewName) select StudentName from Student;
效果图:
修改(update):
update Student set StudentName='赵四成' where id=4
效果图:
删除(delete):
使用delete删除要注意,如果不加where条件,整个表都将被删除。delete删除是物理删除,通常情况下这些数据是无法直接从数据库中恢复的。
--delete删除后编号不会重置
delete from Student where id=6
-- 清空表数据,自动编号的列重置,项目上线前,把测试数据全部清空
--truncate table Student
效果图:
查询(select):
1.查询表里所有内容
select * from Student
2.查询一列,查多列
--查一列
select StudentName from Student
--查多列
select Id, StudentName from Student
3.区间查询
select * from Student where Age between 19 and 21;
select * from Student where Age>19 and Age<21;
4.在范围内查询
--在这个范围内查询
select * from Student where StudentName in ('王五','刘芳')
--在这个范围外查询
select * from Student where StudentName not in ('王五','刘芳')
第一行代码效果图
5.模糊查询
--张 开头的名字
select * from Student where StudentName like '张%'
--张 结尾的名字
select * from Student where StudentName like '%三'
--包含 张 字的名字
select * from Student where StudentName like '%三%'
--不是 三 字结尾的名字
select * from Student where StudentName not like '%三'
最后一行的效果图
6.去重
select distinct StudentName from Student
7.别名,重命名
select Id 编号,StudentName 姓名,Age as 年龄,Birthday as 生日 from Student