一、書寫存儲過程[ProductPage]
CREATE PROCEDURE [dbo].[ProductPage]
@PageIndex int,
@PageSize int,
@ReturnCount int output
AS
BEGIN
DECLARE @Start int, @End int
SET @Start = (@PageIndex - 1) * @PageSize
SET @End = @Start + @PageSize + 1
CREATE TABLE #TEMP(
[Index] int primary key not null identity(1,1),
[ProductID] int,
[ProductName] nvarchar(40),
[SupplierID] int,
[CategoryID] int,
[QuantityPerUnit] nvarchar(20),
[UnitPrice] money,
[UnitsInStock] smallint,
[UnitsOnOrder] smallint,
[ReorderLevel] smallint,
[Discontinued] bit)
INSERT INTO #TEMP ([ProductID],[ProductName],[SupplierID],[CategoryID],[QuantityPerUnit],
[UnitPrice],[UnitsInStock],[UnitsOnOrder],[ReorderLevel],[Discontinued])
SELECT * FROM Products
SET @ReturnCount = @@ROWCOUNT
SELECT *, @ReturnCount as CO FROM #TEMP
WHERE [Index] > @Start AND [Index] < @End
RETURN @ReturnCount--((@ReturnCount / @PageSize) + 1)
END
二、使用
using (SqlConnection conn = new SqlConnection(webconnectstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "ProductPage";
SqlParameter[] parms = new SqlParameter[]{
new SqlParameter("@PageIndex", SqlDbType.Int),
new SqlParameter("@PageSize", SqlDbType.Int),
new SqlParameter("@ReturnCount", SqlDbType.Int),
new SqlParameter("@ReturnValue",SqlDbType.Int)
};
parms[0].Value = pageIndex;
parms[1].Value = pageSize;
parms[2].Value = 0;
parms[3].Direction = ParameterDirection.ReturnValue;
foreach (SqlParameter parm in parms)
{
cmd.Parameters.Add(parm);
}
SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
sqlAdapter.Fill(ds);
recodeCount = Convert.ToInt32(parms[3].Value);
if (ds != null && ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count <= 0)
{
ds = null;
}
}
else
{
ds = null;
}
conn.Close();
sqlAdapter.Dispose();
cmd.Dispose();
conn.Dispose();
}
如果存儲過程中沒有RETURN,那麼代碼中的recodeCount的值將會是0。