1. 子查询:把一个结果集让别人继续分析查询的就叫子查询
  2. 子查询如果定义了别名,在查询引用时,必须使用别名
--子查询定义了别名,引用就必须用别名
select id,n
from Person,(select depname as n from Depment ) as d

常用运算符:

  1. in:表示对多个单列结果进行条件匹配
--in例子

select name,age 
from Person
where Age in(select Age from Person where Age < 19)

--any例子:与运算符结合使用,大于表示要大于查询到的结果集

select name,age
from Person
where Age <any(select Age from Person where Age < 19)

exists

--exists:判断是否为空,为空false,否则true

select * from Person
where exists(select * from Depment where id='002')


select * from Person
where exists(
select * from Depment d where d.id = Person.DepID
)

将结果集直接在数据库插入一张新表,多数据插入


  1. --数据量多插入数据:列必须前后对应
    
    create table person3(id int primary key,name varchar(30),age int, depid varchar(20))
    
    insert into person3( id,name,age,depid)
    select ID,Name,Age,DepID from person


    更新,删除类似

  1. Sql注入攻击问题,采用参数化传参形式可解决
  2. 事务:保证数据原子性、一致性、隔离性、持久性
  3. 开窗函数:可以对每一行结果都返回一个值,避免了group by必须分组的问题
  1. select count(*) over() from 表名
  2. select COUNT(*) over(partition by city) from shakerecode  参数意思是根据城市来分组显示出城市的数量
  1. 连接池:访问数据库时所产生的链接验证成功后,当释放连接对象时,数据库就把此连接对象放到了连接池,下次使用时先从连接池找,如果连接池有这个连接对象直接使用,减少验证等消耗。
  1. 打开数据库连接对象的时间要正好,使用完连接对象要尽快释放,这样连接池的利用率高
  2. 连接字符串默认自动打开连接池,如果就想关闭连接池加语法pooling=false;
  1. 子查询分页
--子查询分页
--between (页码-1)*每页条数+1   and  页码*每页条数 
select * from
(
select ROW_NUMBER() over(order by id) as num, * from Student
) t
where t.num between (1-1)*10+1 and 1*10

 创建视图、修改视图分页

go
create view vw_student
as
select * from
(
select ROW_NUMBER() over(order by id) as num, * from Student
) t
where t.num between (1-1)*10+1 and 1*10
go

--修改视图

alter view vw_student
as
select * from
(
select ROW_NUMBER() over(order by id) as num, * from Student
) as t
go

select * from vw_student where num between 10 and 20
  • 事务
--事务

--三个步骤:开始事务,提交事务,或者回滚事务

begin transaction

commit transaction

rollback transaction

set @@error  --记录最近一次数据操作的错误,如果没有错误默认是0

select @@error
  • 存储过程
  • 存储过程结合事务+变量+参数返回值,执行转账例子
go
create proc usp_BankToBank
@from nvarchar(10),
@to nvarchar(10),
@money money,
@issuccess int output
as
declare @myError int
set @myError = 0
begin
begin tran
update Bank set MoneyVal-=@money where ID = @from
set @myError = @myError+@@ERROR
update Bank set MoneyVal += @money where ID=@to
set @myError = @myError+@@ERROR
if @myError > 0
begin
set @issuccess = 0
rollback tran
end
else
begin
set @issuccess = 1
commit tran
end
end
go

declare @res int
exec usp_BankToBank '001','002',200,@res output
select @res
  •  存储过程分页
create proc usp_StudentPage
@pageIndex int,
@pageCount int
as
begin
select * from
(
select ROW_NUMBER() over(order by id) as num,* from Student
) t
where t.num between (@pageIndex-1)*@pageCount + 1 and @pageIndex*@pageCount
end
go;

exec usp_StudentPage 2,20
  •  触发器
alter trigger tr_删除触发器 on bank
after
delete
as
insert into Bank(ID,moneyval)
select * from deleted;
  • 获取新增数据本身值
-获取最近一次插入数据的值

insert into Bank(ID,MoneyVal) output inserted.* values('004',20)