SQL Server 表的相关应用

创建(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 

 

 

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值