在C#中實現SQL Server的分頁查詢,可以使用以下幾種方法:
using System;
using System.Data.SqlClient;
namespace SqlServerPagination
{
class Program
{
static void Main(string[] args)
{
string connectionString = "your_connection_string";
int pageNumber = 1;
int pageSize = 10;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = $@"
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber
FROM YourTable
) AS PagedTable
WHERE RowNumber BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize)";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@PageNumber", pageNumber);
command.Parameters.AddWithValue("@PageSize", pageSize);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"Id: {reader["Id"]}, Name: {reader["Name"]}");
}
}
}
}
}
}
}
using System;
using System.Data.SqlClient;
namespace SqlServerPagination
{
class Program
{
static void Main(string[] args)
{
string connectionString = "your_connection_string";
int pageNumber = 1;
int pageSize = 10;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = $@"
SELECT *
FROM YourTable
ORDER BY Id
OFFSET (@PageNumber - 1) * @PageSize ROWS
FETCH NEXT @PageSize ROWS ONLY";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@PageNumber", pageNumber);
command.Parameters.AddWithValue("@PageSize", pageSize);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"Id: {reader["Id"]}, Name: {reader["Name"]}");
}
}
}
}
}
}
}
請注意,將your_connection_string
替換為你的SQL Server連接字符串,并將YourTable
替換為你要查詢的表名。這兩個示例都使用了分頁參數pageNumber
和pageSize
,你可以根據需要調整這些值。