關於vs調用數據庫存儲過程 返回輸出參數的一些總結


1.直接上練習的存儲過程,方便回想

create proc proc_output
@totlecount int output,
@pageIndex int,
@pageSize int
as
declare @filter Nvarchar(800)
if OBJECT_ID('Test.dbo.#temp3','U') IS NOT NULL
begin
drop table #temp3
end
set @filter='select identity(int,1,1) as id,* into #temp3 from (
select name from t1 group by name
) as table2;
select * from #temp3 where id between '+CONVERT(VARCHAR(8),(@pageSize*(@pageIndex-1)+1))+' and '+CONVERT(VARCHAR(8),@pageIndex*@pageSize)+';
select @Count=count(1) from #temp3'
exec sp_executesql @filter,N'@Count int output',@totlecount output

2.在執行這個存儲過程時,報錯:

消息 214,級別 16,狀態 2,過程 sp_executesql,第 3 行
過程需要類型為 'ntext/nchar/nvarchar' 的參數 '@statement'。

原因是:需要將定義的@filter 定義為Nvarchar類型,當定義為varchar時會出現上述錯誤。

3.在數據庫執行存儲過程的結果:

4.原本的想法是:數據庫進行了復雜的查詢(當進行多表聯合查詢以及select查詢拼接新表時)得到臨時表,

想省去一個單獨查詢符合分頁條件總數量的存儲過程原因是要進行相同的臨時表創建,當數據量特別大時頁面相應的時間

會比較長。現實是讀數據需要調用ExecuteReader方法讀取數據,想要得到output參數需要調用ExecuteNonQuery方法得到

輸出參數。當調用ExecuteReader方法時,DAL層 param[0].Direction = ParameterDirection.Output;

totleCount =param[0].Value == DBNull.Value ? 0 : Convert.ToInt32(param[0].Value);  這時候的param[0].Value 值為null;

當再調用ExecuteNonQuery方法時,會得到6;(作為一個坑總結一下)

5.那么問題出來了 ,還是調用了兩次同一個存儲過程,換句話說數據庫的查詢量並沒有減少...........

6.於是乎在返回的表里臨時添加了一列,記錄符合條件的總的信息條數。

將存儲過程的“select * from #temp3 where id between '+CONVERT(VARCHAR(8),(@pageSize*(@pageIndex-1)+1))+' and '+CONVERT(VARCHAR(8),@pageIndex*@pageSize)+';
select @Count=count(1) from #temp3” 修改為了“select * ,

(select count(1) from #temp3) as totleCount

from #temp3 where id between '+CONVERT(VARCHAR(8),(@pageSize*(@pageIndex-1)+1))+' and '+CONVERT(VARCHAR(8),@pageIndex*@pageSize)+'”

這樣調用ExecuteReader方法時,就會得到符合查詢條件的信息條數。缺點是返回的每一條數據都有這個信息。

所以需要判斷得到list的長度,當>0時,獲取list[0].totleCount即是總條數否則為0

7.修改完成的存儲過程

alter proc proc_output
@pageIndex int,
@pageSize int
as
declare @filter Nvarchar(800)
if OBJECT_ID('Test.dbo.#temp3','U') IS NOT NULL
begin
drop table #temp3
end
set @filter='select identity(int,1,1) as id,* into #temp3 from (
select name from t1 group by name
) as table2;
select *,(select count(1) from #temp3) as totleCount from #temp3 where id between '+CONVERT(VARCHAR(8),(@pageSize*(@pageIndex-1)+1))+' and '+CONVERT(VARCHAR(8),@pageIndex*@pageSize)+';
'
exec (@filter)

8.執行結果:

9.想多了系列


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM