常见实用sql语句(待更新)

1.分页写法

select top 页大小 *
from table1
where id>(select max (id) from (select top ((页码-1)*页大小) id from table1 order by id) as T) order by id 

 

select * from (
SELECT row_number() OVER (ORDER BY a.oid desc) as rownum__identy,
a.oid, a.title,b.name from a inner join b on a.oid=b.reloid
)

t   where rownum__identy between  20000 and 20015 Order By  oid desc

 

2.删除重复行

with orders as
(select row_number()over(order by OID)Oid,uSERNAME,USERPWD,EMAIL,REMARK from dbo.[User])

//建立rowNumber,以此标识某列,此处可不用,因为有OID

delete orders from
(select min(oid)as id,USERNAME,USERPWD,EMAIL,REMARK from ORDERS group by USERNAME,USERPWD,EMAIL,REMARK  having count(*)>1)
as del
where orders.USERNAME = del.USERNAME
and orders.UserPwd = del.UserPwd
and orders.Email = del.Email
and orders.Remark = del.Remark
and orders.OID!=del.id

3.分页存储过程

/*=========================================
创建日期:2008-5-12
作  者:Xu Yu
对象名称:pr_sys_pager
主要功能:通用分页(带排序)
参数描述:@p_sql varchar(50),         --产生数据集的SQL语句

  @p_field varchar(10),        --排序字段

  @p_order varchar(5),           --排序顺序

  @p_pageSize int,               --每页大小

  @p_currentPage int,        --当前页码

  @p_rowCount int output,      --返回总记录数

  @p_pageCount int output      --返回总分页数
==========================================*/

create procedure [dbo].[pr_sys_pager]

(
  @p_sql nvarchar(max),          --产生数据集的SQL语句

  @p_pageSize int,             --每页大小

  @p_currentPage int,          --当前页码

  @p_fieldOrder nvarchar(50),        --排序方式


  @p_rowCount int output,      --返回总记录数

  @p_pageCount int output      --返回总分页数
)

as

  declare @v_sql nvarchar(max);

  declare @v_start int;  --提取记录的开始位置

  declare @v_end int;    --提取记录的结束位置

begin

     --------------------返回总记录数

     set @v_sql = 'select @a=count(*) from (' + @p_sql + ') t';

     execute sp_executesql @v_sql,N'@a int output' , @p_rowCount output;

    --------------------返回总分页数

     set @p_pageCount = ceiling( convert(float , @p_rowCount) / @p_pageSize);

 
     --------------------得到提取记录的开始和结束位置

     set @v_end = @p_currentPage * @p_pageSize;

     set @v_start = @v_end - @p_pageSize + 1;

     ---------------------获取当前数据记录

     set @v_sql = 'select * from ( select t.* , row_number() over (order by ' + @p_fieldOrder + ') rn from (' + @p_sql + ') t) tt
                  where rn between ' + convert(nvarchar(10) , @v_start) + ' and ' + convert(nvarchar(10) , @v_end) + '';

--print @v_sql

     execute sp_executesql @v_sql;

end;

你可能感兴趣的:(sql语句)