I try to input value but #numVal doest not work ( on the line begin with arr[10] )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MySqlConnection conDatabase = new MySqlConnection("Data Source=localhost;" +
"Persist Security Info=yes;" +
"UserId=tee; PWD=t5794849; database=ph3;");
conDatabase.Open();
// MySqlCommand cmdDatabase = new MySqlCommand("DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc;", conDatabase);
Console.WriteLine("Enter username");
string input = Console.ReadLine();
try
{
int numVal = Convert.ToInt16(input);
}
catch (FormatException )
{
Console.WriteLine("Input string is not a sequence of digits.");
}
catch (OverflowException )
{
Console.WriteLine("The number cannot fit in an Int32.");
}
string[] arr = new string[11];
arr[0] = "UPDATE `member` SET `amphurecode`= SUBSTRING(member.own,3,4)";
arr[1] = "UPDATE `member` SET `provincecode`= SUBSTRING(member.own,3,2)";
arr[2] = "DROP TABLE IF EXISTS `q_mem_tim`; create table q_mem_tim as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.novote, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE";
arr[3] = "DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc";
arr[4] = "DROP TABLE IF EXISTS `q_mem_hno` ; create table q_mem_hno as select member.Hno, member.Moo, member.tambol, COUNT( member.Hno ) AS cntHno, COUNT(DISTINCT member.Ssurname) as NoSur FROM member GROUP BY member.Hno, member.Moo, member.tambol ORDER BY cntHno DESC ";
arr[5] = "DROP TABLE IF EXISTS `q_pro_ori`; create table q_pro_ori as Select member.provincecode, count(*) As cnt From member Group By member.provincecode Order By cnt Desc ";
arr[6] = "DROP TABLE IF EXISTS `q_am_ori`; create table q_am_ori as Select member.amphurecode, member.provincecode, count(*) As cnt From member Group By member.amphurecode, member.provincecode Order By cnt Desc ";
arr[7] = "DROP TABLE IF EXISTS `Sur_Hno_`; create table Sur_Hno_ as SELECT count( * ) , Ssurname, q_mem_tim.Hno, q_mem_tim.Moo, q_mem_tim.tambol FROM q_mem_tim GROUP BY q_mem_tim.Ssurname, q_mem_tim.Hno, q_mem_tim.Moo, q_mem_tim.tambol ORDER BY count( * ) DESC";
arr[8] = "DROP TABLE IF EXISTS `q_dup_own`; create table q_dup_own as SELECT Count(*) as n ,member.own FROM member GROUP BY member.own order by n DESC ";
// arr[9] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, member.fathercode , member.mathercode, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d ,member.inputstaf FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE WHERE DAYOFYEAR(member.dateofbirth)-DAYOFYEAR(NOW()) < 30 and DAYOFYEAR(member.dateofbirth)-DAYOFYEAR(NOW()) > -1 order by DAYOFYEAR(member.dateofbirth)";
arr[9] = "ALTER TABLE `q_mem_tim` ADD `agec` VARCHAR( 10 ) NULL ";
// arr[10] = "UPDATE q_mem_birth SET agec = CASE WHEN y < 10 THEN 'ด' WHEN y > 10 and y < 20 and Sex='ญ' THEN 'วญ' WHEN y > 10 and y < 20 and Sex='ช' THEN 'วช' ELSE 'ผญ' END";
arr[10] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT q_mem_tim.idmember,q_mem_tim.own,q_mem_tim.PROVINCE_NAME,q_mem_tim.AMPHUR_NAME,q_mem_tim.novote,q_mem_tim.Sname,q_mem_tim.Ssurname,q_mem_tim.Hno,q_mem_tim.Moo,q_mem_tim.Sex,q_mem_tim.tambol,q_mem_tim.dateofbirth,q_mem_tim.migratedate,q_mem_tim.y,q_mem_tim.d,q_mem_tim.agec FROM q_mem_tim where q_mem_tim.dateofbirth is not null and q_mem_tim.dateofbirth != '00000000' and day(q_mem_tim.dateofbirth) != '00' and day(q_mem_tim.dateofbirth) > 0 and day(q_mem_tim.dateofbirth) < 11 and month(q_mem_tim.dateofbirth) != '00' and month(q_mem_tim.dateofbirth) = #numVal order by tambol,Moo, month(dateofbirth),day(dateofbirth) ";
foreach (string s in arr)
{
Console.WriteLine(s);
MySqlCommand cmdDbase = new MySqlCommand((s), conDatabase);
cmdDbase.CommandTimeout = 500;
cmdDbase.ExecuteNonQuery();
}
conDatabase.Close();
}
}
}
1)Truncate the tables; don't drop them and remake them because when you drop them you have to do the indexes and add the Primary Keys again.
using(var cm = _dbConnection.CreateCommand())
{
cm.CommandText = #"Truncate Table Table";
cm.CommandType = CommandType.Text;
cm.ExecuteNonQuery();
}
2)Don't forget the # symbol; it helps with anything SQL:
using(var cm = _dbConnection.CreateCommand())
{
cm.CommandText = #"Select *
From table
Where Id = #Id";
cm.CommandType = CommandType.Text;
cm.Parameter.AddWithValue("Id", id);
cm.ExecuteNonQuery();
}
I know you're not doing it this way and you're using a string array (just put a foreach loop outside the using statement and replace the cm.CommandText value with the string's value) but with the examples it should help you or at least give you some ideas.
You need to add a MySqlParameter to the command named numVal.
Related
How does a SQL Server query select from parameter? I just want to make it simple set select column based on my C# code. Is it possible?
Here is my stored procedure:
ALTER PROCEDURE [dbo].[GetMembersDetailGenerateChanceTop10000]
#EventId nvarchar(255),
#PeriodId nvarchar(255),
#QueryParam nvarchar(1000)
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT TOP 10000 #QueryParam
FROM ign..Chance_Generated cg
INNER JOIN ign..Contact c ON cg.ContactID = c.ContactId
LEFT JOIN ign..CustomerAddress ca ON ca.parentid = cg.contactid
LEFT JOIN ign..new_cardlevelconfig cl ON cl.new_cardlevelconfigid = c.new_cardlevel
LEFT JOIN ign..new_country co ON co.new_countryid = c.new_country
LEFT JOIN ign..new_province po ON po.new_provinceId = c.new_Province
LEFT JOIN ign..StringMap sm ON sm.AttributeValue = c.new_IDType
LEFT JOIN ign..new_city cy ON cy.new_cityId = c.new_CityCounty
LEFT JOIN ign..new_transactionheader th ON cg.New_Name COLLATE DATABASE_DEFAULT = th.new_name COLLATE DATABASE_DEFAULT
WHERE cg.EventId = #EventId
AND (ca.AddressNumber = '1' OR ca.AddressNumber IS NULL)
AND (sm.AttributeName IS NULL OR sm.AttributeName = 'new_idtype')
AND cg.periodId = #PeriodId
QueryParam, EventId, PeriodId will be filled from C# code.
Here is my C# code:
private List<GenerateModel> getDataTopFromStoreProcedure(string EventId, string PeriodId)
{
// query select parameter
string QueryParam = #"cg.Chance_Number, th.new_name as [th name], dateadd(HOUR,7,th.createdon) as [th createdon],
c.new_Initial, c.FirstName, c.LastName";
string ConnString = GenerateChance.Properties.Settings.Default["DB_ConnectionString"].ToString();
using (SqlConnection conn = new SqlConnection(ConnString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = GetMembersDetailGenerateChanceTop10000;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0; //no limit
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("QueryParam", QueryParam));
cmd.Parameters.Add(new SqlParameter("EventId", EventId));
cmd.Parameters.Add(new SqlParameter("PeriodId", PeriodId));
cmd.Connection = conn;
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new GenerateModel
{
ChanceNumber = reader["Chance_Number"].ToString(), //System.IndexOutOfRangeException Error
Receipt = reader["th name"].ToString(),
Date = reader["th createdon"].ToString(),
Initial = reader["new_Initial"].ToString(),
FirstName = reader["FirstName"].ToString(),
LastName = reader["LastName"].ToString(),
});
}
reader.Close();
}
}
return list;
}
I am confused as to how to implement his method because I want to get return of all select results in object model but I always get error
System.IndexOutOfRangeException : Chance_Number.
Honestly why do I use query select parameter is because I want to get value from checkedListBox1 that already I defined before by using this code get all checkedListBox1 value to determine select query.
string QueryParam = "cg.Chance_Number";//auto get chance_number as select mandatory
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
QueryParam += ", " + ((clsItemList)checkedListBox1.CheckedItems[i]).Value;
}
You have to use constructor with proper length for parameters as given below, to avoid the issue.Read more on SQLParameter
public SqlParameter (string parameterName, System.Data.SqlDbType dbType, int size);
cmd.Parameters.Add(new SqlParameter("QueryParam", SqlDbType.NVarChar,1000)).Value = QueryParam;
You need to make few more changes:
The way you have defined the procedure is wrong. You have to define the procedure as dynamic sql for the #queryparam to get concatenated to the SELECT query as given below:
DECLARE #selectStmt NVARCHAR(MAX) = ''
DECLARE #sqldefinition NVARCHAR(4000) = '#EventId nvarchar(255), #PeriodId nvarchar(255)'
SET #selectStmt += 'select distinct top 10000 ' + #QueryParam +
'from ign..Chance_Generated cg
inner join ign..Contact c on cg.ContactID = c.ContactId
left join ign..CustomerAddress ca on ca.parentid = cg.contactid
left join ign..new_cardlevelconfig cl on cl.new_cardlevelconfigid = c.new_cardlevel
left join ign..new_country co on co.new_countryid = c.new_country
left join ign..new_province po on po.new_provinceId = c.new_Province
left join ign..StringMap sm on sm.AttributeValue = c.new_IDType
left join ign..new_city cy on cy.new_cityId = c.new_CityCounty
left join ign..new_transactionheader th on cg.New_Name COLLATE DATABASE_DEFAULT = th.new_name COLLATE DATABASE_DEFAULT
where cg.EventId= '''+ #EventId +''' and (ca.AddressNumber = ''1'' or ca.AddressNumber is null) and (sm.AttributeName is null or sm.AttributeName = ''new_idtype'')
and cg.periodId = ''' + #PeriodId + ''';'
EXEC #sp_executesql #selectStmt, #sqldefinition, #EventId , #PeriodId
``
- Always refer the tables with proper schema in the query
ign.SchemaName.new_country
ign.SchemaName.new_province
I have a Big doudt.
I'm trying to load my data with this code:
SqlConnection con = new SqlConnection(Login.conectData);
con.Open();
DataSet dsFabricantes = new DataSet();
SqlDataAdapter daFabricantes = new SqlDataAdapter("SELECT TOP 100 * FROM
Fabricantes", con);
dsFabricantes.Clear();
//prencher a tabela
daFabricantes.Fill(dsFabricantes, "Fabricantes");
tabelaFabricantes.DataSource = dsFabricantes;
tabelaFabricantes.DataMember = "Fabricantes";
//para mudar o que está escrito no cabeçalho das colunas
tabelaFabricantes.Columns[1].HeaderCell.Value = "Nome do
Fabricante";
tabelaFabricantes.Columns[2].HeaderCell.Value = "Observações";
con.Close();
tabelaFabricantes.ClearSelection();
I Want to make a button to load more register in my datagridView. Onload of the app I am changing just 100 register. My question is:
How can I add a button to onClickbutton this button, my dataGrideView, Load more 100 Register and so on and so on ?
little Help
thank you
Bráulio José
You'll need to dynamically adapt your SqlDataAdapter() call.
First set some global variables on page/formOnLoad method
global int startRow = '1';
global int maxColRank = testMaxRows();
#set left button active = false
leftButton.Active = false;
To do this, class your DataGridViewLoader separately to accept no parameters. Name the class mySqlGridViewLoaderClass()
at the beginning of this class input these values:
string MaximumRows = '100';
string StartRowIndex = StartRow.ToString();
In the SQL connector for this DataGridViewLoader, use a query similar to
SELECT colRank, col1, col2
FROM
(SELECT col1, col2,
ROW_NUMBER() OVER(ORDER BY col2 DESC) AS colRank
FROM Fabricantes
) AS rowNumQuery
WHERE colRank > <i>StartRowIndex</i> AND
colRank <= (<i>StartRowIndex</i> + <i>MaximumRows</i>
)
Your class should perform DataGridView loading operation, then return a second scalar value for MAX(colRank).
#new connector
SqlDataAdapter daFabricantes = new SqlDataAdapter("SELECT Max(colRank) FROM
(SELECT max(colRank)
FROM
(SELECT col1, col2,
ROW_NUMBER() OVER(ORDER BY col2 DESC) AS colRank
FROM Fabricantes
) AS rowNumQuery
WHERE colRank > <i>StartRowIndex</i> AND
colRank <= (<i>StartRowIndex</i> + <i>MaximumRows</i>
))", con2);
int mr = (Int32) con2.ExecuteScalar();
return mr;
class a second SQL connector loader to test max Rows and return a scalar value. name the class testMaxRows()
In the sql connector, use a query similar to:
Select count(col1) DIST from fabricantes;
Return the count to the tr variable. The last 2 lines of maxRows class should be:
int tr = (Int32) con.ExecuteScalar();
return tr;
In your form designer, create a button for '<' and '>'
Set < button to inactive. > button to active
In the '<' ButtonOnClick() event:
rightButton.Active = true;
if (StartRow != '1')
{
StartRow -= 100;
# your class expects a return value, so we'll initialize one
int mr = (Int32) mySqlGridViewLoaderClass();
if (StartRow == 1)
{
leftButton.Active = false;
}
}
In the '>' ButtonOnClick() event:
leftButton.Active = true;
StartRow += 100;
int maxRank = (Int32) mySqlGridViewLoaderClass();
if ( maxRank >= maxColRank)
{
rightButton.Active = false;
}
I have a problem with mySql query below
SELECT name, hospitalID, currentAvgRating, rank
FROM ( SELECT name,hospitalID,currentAvgRating,city,
#curRank := #curRank + 1 AS rank
FROM hospitals h, ( SELECT #curRank := 0) r
ORDER BY currentAvgRating DESC
) toplist
WHERE toplist.hospitalID = #hospitalID
and city = #city
This query I am using to find the rank of particular item & it is working properly. But while runining in program I get Fatal errors of Parameter '#curRank' must be defined. But that is mysql syntax then how can I get it's parameters?
UPDATE
string str = "SELECT name, hospitalID, currentAvgRating, rank FROM (SELECT name,hospitalID,currentAvgRating,city,#curRank := #curRank + 1 AS rank FROM hospitals h, (SELECT #curRank := 0) r ORDER BY currentAvgRating DESC) toplist WHERE toplist.hospitalID = #hospitalID and city = #city";
con.Open();
MySqlCommand cmd = new MySqlCommand(str, con);
cmd.Parameters.AddWithValue("#hospitalID", generalID.Text);
cmd.Parameters.AddWithValue("#city", cityName.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
You can get the rank for a particular hospital/city pair without a rank. Here is a close approximation to your query:
select count(*) + 1 as ranking
from hospitals h cross join
(select h.currentAvgRating
from hospitals h
where h.hospitalID = #hospitalID and h.city = #city
) hh
where h.currentAvgRating > hh.currentAvgRating;
Unlike your code, this gives all hospitals with the same rating, the same ranking.
If you don't want to change the code, then refer to this answer. Actually, I'll quote the relevant part:
I have to add
;Allow User Variables=True
to the connection string
Your SQL is correct I think there are conflect with C# command parameter and mySQL parameter
try this modification of SQL code like this
SELECT name, hospitalID, currentAvgRating, rank
FROM ( SELECT name,hospitalID,currentAvgRating,city,
#curRank := #curRank + 1 AS rank
FROM hospitals h, ( SELECT #curRank := 0) r
ORDER BY currentAvgRating DESC
) toplist
WHERE toplist.hospitalID = ?hospitalID
and city = ?city
you c# like this
string str = <Example Above>;
con.Open();
MySqlCommand cmd = new MySqlCommand(str, con);
cmd.Parameters.AddWithValue("?hospitalID", generalID.Text);
cmd.Parameters.AddWithValue("?city", cityName.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
Just changeing the C# command parameter using ? than using #
I have a SQL Server database with a couple tables with records. My input is IMEI number that I must store in a table only if this IMEI number is not saved in all tables. my code is:
public int Find_IMEI(string IMEI_NUM)
{
IMEI_lab.Text = IMEI_NUM.ToString();
int dflag = 0;
object result;
SqlConnection sqlConn = new SqlConnection(#"Data Source=\SQLEXPRESS;Initial Catalog=manager_db;Integrated Security=True;Pooling=False");
sqlConn.Open();
int test = 0;
for(int kk = 0; kk < comboBox2.Items.Count; kk++)
{
string data_sql = string.Format("IF EXISTS(SELECT 1 FROM {0} WHERE IMEI={1}) SELECT 1 AS FOUND ELSE SELECT 0 AS FOUND", data[kk], IMEI_NUM);
SqlCommand da = new SqlCommand(data_sql, sqlConn);
result = da.ExecuteScalar(); // ExecuteScalar fails on null
if (result.GetType() == typeof(DBNull)) // checking IMEI number in all Tables(orders)
{
dflag = 0;
test = test + dflag;
}
else
{
dflag = (int)result; //(Int32)da.ExecuteScalar();
test = test + dflag;
}
}
sqlConn.Close();
return test;
}
This code is working fine, returns count of found duplicate IMEI numbers in all tables. But I want to know if SQL has query that do the job in more optimize way or without loops
Table definition :
id | IMEI | Serial | date
----------------------------------------
1 3548690... 0001 15/2/15
2 3548690... 0002 15/2/15
P.S data[kk] - array with tables names
You can send the single request to SQL server instead N requests, where N is the number of your tables, using the UNION clause.
You need some like this request:
SELECT SUM(C) FROM
(
SELECT COUNT(*) AS C FROM {Table1} WHERE IMEI = #IMEI
UNION
SELECT COUNT(*) AS C FROM {Table2} WHERE IMEI = #IMEI
UNION
. . .
UNION
SELECT COUNT(*) AS C FROM {TableN} WHERE IMEI = #IMEI
)
As far as I understand, your data[] array stores the names of tables.
var tableRequests = data.Select(tableName => string.Format("SELECT COUNT(*) AS C FROM [{0}] WHERE IMEI = #IMEI", tableName));
var innerRequest = string.Join(" UNION ", tableRequests);
var finalRequest = string.Format("SELECT SUM(C) FROM ({0})", innerRequest);
using (var command = new SqlCommmand(finalRequest, sqlConn))
{
commman.Parameters.Add("#IMEI", IMEI_NUM);
return (int)command.ExecuteScalar();
}
var tableRequests = data.Select(tableName => string.Format("SELECT COUNT(*) AS C FROM {0} WHERE (IMEI = {1})", tableName, IMEI_NUM));
var innerRequest = string.Join(" UNION ", tableRequests);
var finalRequest = string.Format("SELECT SUM(C) AS EXP FROM ({0}) AS ANS", innerRequest);
using (var command = new SqlCommand(finalRequest, sqlConn))
{
return (int)command.ExecuteScalar();
}
thanks to #Mark Shevchenko
What is the correct way of writing a select statment on c# controller for paging. This is the best I came up with, but I know it doesn't work because it's showing all data on my first page on the grid... please help
public JsonResult getData(int start, int limit)
{
List<MyItem> items = new List<MyItem>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT State, Capital FROM MYDBTABLE";
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MyItem item = new MyItem();
item.State = reader[0].ToString();
item.Capital = reader[1].ToString();
items.Add(item);
}
con.Close();
if ((start + limit) > Myitem.Count)
{
limit = Myitem.Count - start;
}
return Json(new { myTable = items }, JsonRequestBehavior.AllowGet);
}
}
Here's the template for stored procs that I like to use for paging.
CREATE PROCEDURE [dbo].[StoredProcName]
#page_size INT
, #page_num INT
AS
BEGIN
SET NOCOUNT ON;
; WITH RESULTS AS
(
SELECT *
, ROW_NUMBER() OVER (ORDER BY <order_col> DESC) AS rn
, ROW_NUMBER() OVER (ORDER BY <order_col> ASC) AS rn_reversed
FROM <table>
)
SELECT *
, CAST(rn + rn_reversed - 1 AS INT) AS total_rows
, CAST(CASE (rn + rn_reversed - 1) % #page_size
WHEN 0 THEN (rn + rn_reversed - 1) / #page_size
ELSE ((rn + rn_reversed - 1) / #page_size) + 1
END AS INT) AS total_pages
FROM RESULTS a
WHERE a.rn BETWEEN 1 + ((#page_num - 1) * #page_size) AND #page_num * #page_size
ORDER BY rn ASC
END
You just need to pass in page_size and page_num to the stored proc and you're good to go.
You could use Linq and use Skip() and Take() like this:
public JsonResult getData(int page, int limit)
{
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionString))
{
using (SqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT State, Capital FROM MYDBTABLE";
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
int start = (page * limit) - limit;
List<MyItem> items = (from DataRow row in dt.Rows
select new MyItem
{
State = row["State"].ToString(),
Capital = row["Capital"].ToString()
}).Skip(start - 1).Take(limit).ToList();
return Json(new { myTable = items }, JsonRequestBehavior.AllowGet);
}
The basic template I use is:
SELECT ROW_NUMBER(), <Rest of your columns>
FROM <Your Tables/Joins>
WHERE ROW_NUMBER() >= (#PageNum * #RowsPerPage)
AND ROW_NUMBER() < (#PageNum+1 * #RowsPerPage)