简介

本文主要介绍下述几个技巧:

  • 使用Row_Number分页
  • 事务
  • 根据条件刷选记录的技巧

分页

主要是使用了Row_Number()这个函数。一般如下:

declare @PageSize int;
declare @StartIndex int;

with MyTable_Paged as(
    select 
        Row_Number() over(order by col_1) as '',
        *
    from
        MyTalbe
    where
        condition
)
select * from MyTable_Paged

where RowNumber between StartIndex and StartIndex+@PageSize-1

事务

这个在复杂的sql语句中经常用,尤其配合存储过程。能够使一个操作原子化,防止只执行部分的操作。(当一个存在过程在执行的时候,是一条一条语句执行的,当出现错误的时候回停止执行,但是如果前面已经执行了一些语句,那么没有事务机制的话,该执行不能够回滚。)

begin try
    begin tran
        sqlstatement
    commit tran
end try
begin catch
    rollback tran
end catch

根据条件刷选记录

这个技巧在于当某一个条件可用可不用的情况下,不必使用众多的if等条件选择语句
比如需要筛选的条件如下:Name,Phone,Email

select * from MyTalbe where 
    ([Name]=@Name or @Name is null)
and
    (Phone=@Phone or @Phone is null)
and
    (Email=@Email or @Email is null)

相关文章:

  • 2022-12-23
  • 2022-01-29
  • 2022-02-13
  • 2021-12-02
  • 2021-12-26
  • 2021-06-24
  • 2021-08-01
猜你喜欢
  • 2022-03-04
  • 2022-01-10
  • 2021-06-17
  • 2022-12-23
  • 2021-06-12
  • 2021-12-04
相关资源
相似解决方案