ASP執行存儲過程經驗談

1,利用SQL SERVER游標,這种方法的優點:適用性比較強,性能不是很好.存儲過程如下:
CREATE PROC SP_PageView
@Sql varchar(
8000), ---SQL語句
@PageCurNum 
int=1,          ---當前頁,如果為空則為第一頁
@PageSize 
int=10         ---每頁行數,黑認為10
as
set nocount on 
declare @Cur 
int,@RowCount int,@PageStartRow int,@PageCount int
--計算出一共有多少條數據
exec sp_cursoropen @Cur output,@Sql,@scrollopt
=1,@ccoppt=1,@RowCount=@RowCount output
--計算出有多少頁
set @PageCount=ceiling(1.0*@RowCount/@PageSize)
--如果當前頁大於最大頁時
if @PageCurNum>@PageCount
  begin
    
set @PageCurNum=@PageCount
    
set @PageStartRow=(@PageCount-1)*@pagesize+1
  end
else
  begin
    
set @PageStartRow=(@PageCurNum-1)*@PageSize+1
  end

select @PageCount 
as PageCount,@RowCount as RowsCount,@PageCurNum as PageCurNum

exec sp_cursorfetch @Cur,
16,@PageStartRow,@PageSize
exec sp_cursorclose @Cur
set nocount off
GO
在ASP中執行的調用的代碼如下:
'前面定義好SQL語句,例如sql="SELECT * FROM TABLE"
'定議頁面和pagesize
'
this_page=self_url or "?"
this_pagesize=pagesize_30
'對pagenum進行分析
p=request("p")
if IsNumeric(p) then
  p
=clng(p)
  
if p<=0 then p=1
else
  p
=1
end if
'建立物件
Set rs = Server.CreateObject("ADODB.Recordset")
set conn=opendb()'聯接資料庫
Set cmd=Server.CreateObject("ADODB.Command")
with cmd
  .ActiveConnection 
= conn          'conn是聯接數據庫字符串
  .CommandText      = "SP_PageView"     '存儲過程名稱
  .CommandType      = 4                 '說明這是一個存儲過程
  .Prepared         = true              '要求要命預編譯
  .Parameters.append .CreateParameter("@sql",200,1,8000,sql)
  .Parameters.append .CreateParameter(
"@pagecurnum",3,1,4,p)
  .Parameters.append .CreateParameter(
"@pagesize",3,1,4,this_pagesize)
  
Set rs=.Execute
end with
Set rs = rs.NextRecordset()
'因為第一數據集是一個空的 如果驅動用的是oledb的時候則需要這一句
'
如果是sql server的話則不需要這一句
RCount=clng(rs(1))
allpage
=clng(rs(0))
Set rs=rs.nextRecordSet()
if not rs.eof then
'接下來的瀏覽數據
要注意的是聯接資料庫的字符建議最好用OLEDB,用OLEDB的時候要注意的是,存儲過程執行後返回的結果有三個結果集,其中第一個是一個空間的結果集,而第二個是數據數和頁數以及當前頁的一個表,最後是我們要瀏覽的結果集.
而如果你用SQL SERVER來聯接資料庫的時候,不知道什麼原因,有時候會有資料沒有辦法顯示出來,還沒有弄明白是為什麼!!!

posted @ 2007-08-23 23:45  Athrun  阅读(262)  评论(0编辑  收藏  举报