Two paging stored procedure code currently in use _mssql

Source: Internet
Author: User
Tags one table rowcount
First, get the total number of rows in the data
Copy Code code as follows:

Set ANSI_NULLS on
SET QUOTED_IDENTIFIER ON
Go
ALTER PROCEDURE [Sq8reyoung]. [Fenye_num]
(
@TableNames NVARCHAR (200),
@Filter nvarchar (200))
As
IF @Filter = '
SET @Filter = ' WHERE 1=1 '
ELSE
SET @Filter = ' WHERE ' + @Filter
EXECUTE (' Select COUNT (*) from ' + @TableNames + ' + @Filter)

The second gets the paging data
Copy Code code as follows:

Set ANSI_NULLS on
SET QUOTED_IDENTIFIER ON
Go
ALTER PROCEDURE [Sq8reyoung]. [Fenye]
@TableNames VARCHAR (200)--table name, can be multiple tables, but cannot be aliased
@PrimaryKey VARCHAR (100),--primary key, can be null, but @order is empty when the value cannot be null
@Fields VARCHAR (200),--the field to be fetched, can be a field of more than one table, can be empty, empty to represent a select *
@PageSize INT,--Number of records per page
@CurrentPage INT,--current page, 0 represents page 1th
@Filter VARCHAR (200) = ',--condition, can be empty without filling in where
@Group VARCHAR (200) = ',--group by, can be empty, without filling group by
@Order VARCHAR (200) = '---sort, can be empty, default by primary key in ascending order, not filled in by
As
BEGIN
DECLARE @SortColumn VARCHAR (200)
DECLARE @Operator CHAR (2)
DECLARE @SortTable VARCHAR (200)
DECLARE @SortName VARCHAR (200)
IF @Fields = '
SET @Fields = ' * '
IF @Filter = '
SET @Filter = ' WHERE 1=1 '
ELSE
SET @Filter = ' WHERE ' + @Filter
IF @Group <> '
SET @Group = ' Group by ' + @Group
IF @Order <> '
BEGIN
DECLARE @pos1 int, @pos2 int
SET @Order = replace (replace (@Order, ' ASC ', ' ASC '), ' desc ', ' desc ')
IF CHARINDEX (' DESC ', @Order) > 0
IF CHARINDEX (' ASC ', @Order) > 0
BEGIN
IF CHARINDEX (' DESC ', @Order) < CHARINDEX (' ASC ', @Order)
SET @Operator = ' <= '
ELSE
SET @Operator = ' >= '
End
ELSE
SET @Operator = ' <= '
ELSE
SET @Operator = ' >= '
SET @SortColumn = replace (replace (@Order, ' ASC ', '), ' DESC ', '), ', '
SET @pos1 = CHARINDEX (', ', @SortColumn)
IF @pos1 > 0
SET @SortColumn = SUBSTRING (@SortColumn, 1, @pos1-1)
SET @pos2 = CHARINDEX ('. ', @SortColumn)
IF @pos2 > 0
BEGIN
SET @SortTable = SUBSTRING (@SortColumn, 1, @pos2-1)
IF @pos1 > 0
SET @SortName = SUBSTRING (@SortColumn, @pos2 +1, @pos1-@pos2-1)
ELSE
SET @SortName = SUBSTRING (@SortColumn, @pos2 +1, LEN (@SortColumn)-@pos2)
End
ELSE
BEGIN
SET @SortTable = @TableNames
SET @SortName = @SortColumn
End
End
ELSE
BEGIN
SET @SortColumn = @PrimaryKey
SET @SortTable = @TableNames
SET @SortName = @SortColumn
SET @Order = @SortColumn
SET @Operator = ' >= '
End
DECLARE @type varchar (50)
DECLARE @prec int
SELECT @type =t.name, @prec =c.prec
From sysobjects o
JOIN syscolumns C on o.id=c.id
JOIN systypes T on C.xusertype=t.xusertype
WHERE o.name = @SortTable and c.name = @SortName
IF CHARINDEX (' char ', @type) > 0
SET @type = @type + ' (' + CAST (@prec as varchar) + ') '
DECLARE @TopRows INT
SET @TopRows = @PageSize * @CurrentPage + 1
PRINT @type
DECLARE @sql NVARCHAR (4000)
SET @Sql = ' DECLARE @SortColumnBegin ' + @type + '
SET RowCount ' + Cast (@TopRows as VARCHAR) + ' SELECT @SortColumnBegin = ' +
@SortColumn + ' from ' + @TableNames + ' + @Filter + ' + @Group + ' ORDER BY ' + @Order + '
SET RowCount ' + CAST (@PageSize as VARCHAR (10)) + '
SELECT ' + @Fields + ' from ' + @TableNames + ' + @Filter + ' and ' + @SortColumn + ' + @Operator + ' @SortColumnBegin ' + ISNULL (@Group, ') + ' ORDER BY ' + @Order + '
--Print (@sql)
Exec (@sql)
End

And the data manipulation class that implements this method
Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Data.SqlClient;
Using System.Data;
Using System.Configuration;
Using Wuqi.webdiyer;
Using Models;
Namespace DAL
{
public class DBHelper
{
public static readonly String conn_string = configurationmanager.connectionstrings["Rymedicalconnectionstring". ConnectionString;
public static SqlDataReader Getreader (String safesql)
{
SqlConnection conn = new SqlConnection (conn_string);
SqlCommand cmd = new SqlCommand (SAFESQL, conn);
SqlDataReader reader = cmd. ExecuteReader (commandbehavior.closeconnection);
Reader. Close ();
return reader;
}
public static SqlDataReader Getreader (String sql, params sqlparameter[] values)
{
SqlConnection conn = new SqlConnection (conn_string);
SqlCommand cmd = new SqlCommand (SQL, conn);
Conn. Open ();
Cmd. Parameters.addrange (values);
SqlDataReader reader = cmd. ExecuteReader (commandbehavior.closeconnection);
Reader. Close ();
Conn. Close ();
return reader;
}
public static DataTable GetDataSet (String safesql)
{
SqlConnection conn = new SqlConnection (conn_string);
DataSet ds = new DataSet ();
SqlCommand cmd = new SqlCommand (SAFESQL, conn);
Conn. Open ();
SqlDataAdapter da = new SqlDataAdapter (cmd);
Da. Fill (DS);
Conn. Close ();
Return DS. Tables[0];
}
public static DataTable GetDataSet (CommandType cmdtype, String cmdtext, params sqlparameter[] cmdparms)
{
SqlConnection conn = new SqlConnection (conn_string);
DataSet ds = new DataSet ();
SqlCommand cmd = new SqlCommand (CMDTEXT, conn);
Conn. Open ();
PrepareCommand (CMD, conn, null, Cmdtype, Cmdtext, cmdparms);
SqlDataAdapter da = new SqlDataAdapter (cmd);
Da. Fill (DS);
Conn. Close ();
Return DS. Tables[0];
}
public static SqlDataReader ExecuteReader (CommandType cmdtype, String cmdtext, params sqlparameter[] cmdparms)
{
SqlCommand cmd = new SqlCommand ();
SqlConnection conn = new SqlConnection (conn_string);
Conn. Open ();
PrepareCommand (CMD, conn, null, Cmdtype, Cmdtext, cmdparms);
SqlDataReader rdr = cmd. ExecuteReader (commandbehavior.closeconnection);
Cmd. Parameters.clear ();
Rdr. Close ();
Conn. Close ();
return RDR;
}
public static Object ExecuteScalar (CommandType cmdtype, String cmdtext, params sqlparameter[] cmdparms)
{
SqlCommand cmd = new SqlCommand ();
using (SqlConnection conn = new SqlConnection (conn_string))
{
Conn. Open ();
PrepareCommand (CMD, conn, null, Cmdtype, Cmdtext, cmdparms);
Object val = cmd. ExecuteScalar ();
Cmd. Parameters.clear ();
Conn. Close ();
return Val;
}
}
public static Object ExecuteScalar (SqlConnection conn, CommandType Cmdtype, String cmdtext, params sqlparameter[] Cmdparm S
{
SqlCommand cmd = new SqlCommand ();
PrepareCommand (CMD, conn, null, Cmdtype, Cmdtext, cmdparms);
Object val = cmd. ExecuteScalar ();
Cmd. Parameters.clear ();
return Val;
}
private static void PrepareCommand (SqlCommand cmd, SqlConnection Conn, SqlTransaction Trans, CommandType cmdtype, string C Mdtext, sqlparameter[] cmdparms)
{
IF (Conn. State!= ConnectionState.Open)
Conn. Open ();
Cmd. Connection = conn;
Cmd.commandtext = Cmdtext;
if (trans!= null)
Cmd. Transaction = trans;
Cmd.commandtype = Cmdtype;
if (cmdparms!= null)
{
foreach (SqlParameter parm in cmdparms)
Cmd. Parameters.Add (Parm);
}
}
public static void ExecuteNonQuery (String sql)
{
SqlConnection conn = new SqlConnection (conn_string);
SqlCommand cmd = new SqlCommand (sql,conn);
Conn. Open ();
Cmd. ExecuteNonQuery ();
Conn. Close ();
}
<summary>
Incoming SQL statement, returning INT
</summary>
<param name= "SQL" ></param>
<returns></returns>
public static int Excutecommand (String sql)
{
SqlConnection conn = new SqlConnection (conn_string);
SqlCommand cmd = new SqlCommand (SQL, conn);
Conn. Open ();
int result = cmd. ExecuteNonQuery ();
Conn. Close ();
return result;
}
<summary>
///
</summary>
<param name= "name" > need pagination to indicate </param>
<param name= "PK" > Primary Key Name </param>
<param name= "Fields" > fields to be taken out, leave blank for *</param>
<param name= "pagesize" > Number of records per page </param>
<param name= "currentpage" > Current page </param>
<param name= "Filter" > conditions, can be empty, do not fill where</param>
<param name= "group" > Group BY, you can be empty without filling group by</param>
<param name= "Order" > Sort, can be empty, default by primary key in ascending order, not fill order by</param>
<returns></returns>
public static DataTable Pagedlist (string Name, String pk, string fields, int pagesize, int currentpage, string Filter, str ing Group, string order)
{
CurrentPage = CurrentPage-1;
DataTable dt = GetDataSet (CommandType.StoredProcedure, "Fenye",
New SqlParameter ("@TableNames", Name),
New SqlParameter ("@PrimaryKey", PK),
New SqlParameter ("@Fields", Fields),
New SqlParameter ("@PageSize", PageSize),
New SqlParameter ("@CurrentPage", CurrentPage),
New SqlParameter ("@Filter", Filter),
New SqlParameter ("@Group", Group),
New SqlParameter ("@Order", order)
);
return DT;
}
public static int Fenye_num (string Name, String Filter)
{
return (int) executescalar (commandtype.storedprocedure, "Fenye_num",
New SqlParameter ("@TableNames", Name),
New SqlParameter ("@Filter", Filter));
}
<summary>
///
</summary>
<param name= "name" > need pagination to indicate </param>
<param name= "PK" > Primary Key Name </param>
<param name= "Fields" > fields to be taken out, leave blank for *</param>
<param name= "pagesize" > Number of records per page </param>
<param name= "currentpage" > Current page </param>
<param name= "Filter" > conditions, can be empty, do not fill where</param>
<param name= "group" > Group BY, you can be empty without filling group by</param>
<param name= "Order" > Sort, can be empty, default by primary key in ascending order, not fill order by</param>
<param name= "OBJANP" > Pass Aspnetpager Controls </param>
<returns></returns>
public static DataTable Paged (string Name, String pk, string fields, int pagesize, int currentpage, string Filter, String Group, string order, Aspnetpager OBJANP)
{
CurrentPage = CurrentPage-1;
DataTable dt = GetDataSet (CommandType.StoredProcedure, "Fenye",
New SqlParameter ("@TableNames", Name),
New SqlParameter ("@PrimaryKey", PK),
New SqlParameter ("@Fields", Fields),
New SqlParameter ("@PageSize", PageSize),
New SqlParameter ("@CurrentPage", CurrentPage),
New SqlParameter ("@Filter", Filter),
New SqlParameter ("@Group", Group),
New SqlParameter ("@Order", order)
);
Objanp. RecordCount = Fenye_num (Name, Filter);
return DT;
}
}
}

And how the page is called
Copy Code code as follows:

Using System;
Using System.Collections;
Using System.Configuration;
Using System.Data;
Using System.Linq;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.HtmlControls;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Xml.Linq;
Using Insus.net;
Using DAL;
Using System.Data.SqlClient;
public partial class News_newlist:System.Web.UI.Page
{
int nid;
int totalorders;
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
if (request.querystring["typeID"]!= null)
{
Nid = Convert.ToInt16 (request.querystring["typeID"). ToString ());
Binddata (1);
}
Else
{
Response.Redirect ("~/default.aspx");
}
}
}
private void Binddata (int page)
{
DataTable dt = dbhelper.paged ("M_newinfoall", "new_id", "" ", Aspnetpager1.pagesize, page," new_typeid= "+ nid. ToString () + "", "", "New_pubdate desc", AspNetPager1);
This. Repeater1.datasource = DT;
This. Repeater1.databind ();
DataRow dr = dt. Rows[0];
This. Label1.Text = dr["New_typename"]. ToString ();
This. Literal1.text = dr["New_typename"]. ToString ();
Page.title = Label1.Text.Trim () + "-New agricultural and pharmaceutical Network";
}
protected void Aspnetpager1_pagechanged (object sender, EventArgs e)
{
if (request.querystring["page"]!= null)
{
Binddata (Convert.ToInt32 (request.querystring["page"). ToString ()));
}
}
}

This can be achieved (the following figure), in any project only need to COPY2 stored procedures a data manipulation class, or like to make data classes into a DLL or, in the page call to pass the parameter only one line of code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.