一、SQL语句分页的四种写法
<!--第一种 top-->
select top(10)* from AdminInfo where Id not in(select top(10) Id from AdminInfo)
<!--第二种 MAX()-->
select top(10) * from AdminInfo where Id>(select MAX(Id)from AdminInfo where Id in (select top(10)Id from AdminInfo))
<!--第三种 between ... and ...-->
select * from AdminInfo where Id between 1 and 20
<!--第四种 ROW_NUMBER()-->
select *from(select *,ROW_NUMBER()over(order by id)as number from AdminInfo)t where t.number between 11 and 20
二、存储
(1)存储的创建方法
create proc 存储名称(@参数名 参数类型)as
declare @变量名 参数类型;
set @变量名=值;
print 输入语句;
注意:1>存储的参数的变量命名使用@符号,在方法里面定义变量是使用 declare,给变量赋值是使用set
2>参数类型是SQL Server Management Studio(数据库)的类型而不是我们使用的Visual Studio 2019里面的类型
3>在新建查询中调用存储使用exec(如果方法有参数,不需使用()传参,直接空格参数,如有多个使用逗号来区隔开,参数为varchar类型使用单引号传值)
(2)存储循环操作
create proc Prceduer(@count int)as
declare @countq int;
set @countq=@count;
while(@countq>0)
begin
print @countq;
set @countq-=1;
End
//在新建查询中调用Prceduer
exec dbo.Prceduer 10
注意:在存储过程中是没有 { }
{ 使用begin
} 使用end
(3)存储sql语句操作
create proc [dbo].[pagelistproc] (@pageIndex int,
@pagesize int,@tableName varchar(200),@columnName varchar(500),@orderby varchar(50),@sort varchar(50)
)as
declare @sql nvarchar(2000);
set @sql='select '+@columnName+' from(select '+@columnName+' ,ROW_NUMBER()over(order by '+@orderby+' )as number from '+@tableName+' )t where t.number between '+cast(((@pageIndex-1)*@pagesize)as varchar(200))+' and '+ cast((@pagesize*@pageIndex) as varchar(200))
exec(@sql)
//在新建查询中调用pagelistproc 参数(第几页,多少条记录,表名,需查询的字段,排序的字段,升序/倒序,)
exec pagelistproc 1,5,'dbo.Admini','*','aID','desc'
注意:1>参数是int类型给varchar赋值是要强转类型使用cast()
2>sql语句的值换成变量使用 ’++‘(单引号++单引号)
3>在单引号的前后都添加一个空格,(如果不添加定义的变量sql就只是一串字符而不是SQL语句)