SQL Server基础:存储过程
作者:网络转载 发布时间:[ 2015/5/8 13:43:12 ] 推荐标签:数据库
(6).不缓存存储过程
--with recompile不缓存
if (object_id('book_temp', 'P') is not null)
drop proc book_temp
go
create proc book_temp
with recompile
as
select * from books;
go
exec book_temp;
exec sp_helptext 'book_temp';
(7).创建带游标参数的存储过程
if (object_id('book_cursor', 'P') is not null)
drop proc book_cursor
go
create proc book_cursor
@bookCursor cursor varying output
as
set @bookCursor=cursor forward_only static for
select book_id,book_name,book_auth from books
open @bookCursor;
go
--调用book_cursor存储过程
declare @cur cursor,
@bookID int,
@bookName varchar(20),
@bookAuth varchar(20);
exec book_cursor @bookCursor=@cur output;
fetch next from @cur into @bookID,@bookName,@bookAuth;
while(@@FETCH_STATUS=0)
begin
fetch next from @cur into @bookID,@bookName,@bookAuth;
print 'bookID:'+convert(varchar,@bookID)+' , bookName: '+ @bookName
+' ,bookAuth: '+@bookAuth;
end
close @cur --关闭游标
DEALLOCATE @cur; --释放游标
(8).创建分页存储过程
if (object_id('book_page', 'P') is not null)
drop proc book_page
go
create proc book_page(
@TableName varchar(50), --表名
@ReFieldsStr varchar(200) = '*', --字段名(全部字段为*)
@OrderString varchar(200), --排序字段(必须!支持多字段不用加order by)
@WhereString varchar(500) =N'', --条件语句(不用加where)
@PageSize int, --每页多少条记录
@PageIndex int = 1 , --指定当前为第几页
@TotalRecord int output --返回总记录数
)
as
begin
--处理开始点和结束点
Declare @StartRecord int;
Declare @EndRecord int;
Declare @TotalCountSql nvarchar(500);
Declare @SqlString nvarchar(2000);
set @StartRecord = (@PageIndex-1)*@PageSize + 1
set @EndRecord = @StartRecord + @PageSize - 1
SET @TotalCountSql= N'select @TotalRecord = count(*) from ' + @TableName;--总记录数语句
SET @SqlString = N'(select row_number() over (order by '+ @OrderString +') as rowId,'+@ReFieldsStr+' from '+ @TableName;--查询语句
--
IF (@WhereString! = '' or @WhereString!=null)
BEGIN
SET @TotalCountSql=@TotalCountSql + ' where '+ @WhereString;
SET @SqlString =@SqlString+ ' where '+ @WhereString;
END
--第一次执行得到
--IF(@TotalRecord is null)
-- BEGIN
EXEC sp_executesql @totalCountSql,N'@TotalRecord int out',@TotalRecord output;--返回总记录数
-- END
----执行主语句
set @SqlString ='select * from ' + @SqlString + ') as t where rowId between ' + ltrim(str(@StartRecord)) + ' and ' + ltrim(str(@EndRecord));
Exec(@SqlString)
END
--调用分页存储过程book_page
exec book_page 'books','*','book_id','',3,1,0;
--
declare @totalCount int
exec book_page 'books','*','book_id','',3,1,@totalCount output;
select @totalCount as totalCount;--总记录数。
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。
相关推荐
远程连接sql server 2000服务器的解决方案SQL Server修改数据库物理文件存在位置探讨SQL Server并发处理队列数据不阻塞解决方案迁移SQL Server到Azure SQL实战SQL SERVER 的前世今生?各版本功能对比SQL Server的WITH (NOLOCK)SQL Server如何用触发器捕获DML操作的会话信息SQL Server里书签查找的性能伤害监控SQL Server事务复制SQL Server数据库镜像下有效的索引维护SQL Server不停机移动镜像数据库SQL Server数据库备份压缩拷贝实例SQL Server数据库优化SQL SERVER的统计信息SQL Server里如何处理死锁SQL SERVER批量生成编号

sales@spasvo.com