没有总行的SQL级别分页

时间:2012-02-28 15:22:42

标签: c# sql-server-2008 tsql .net-3.5 ado.net

是否可以转换以下脚本以便可以直接从ADO .NET调用它?我不希望它是一个存储过程,如果这样可以更容易转换,我不需要TotRows

DECLARE @startRow INT ; SET @startrow = 50
;WITH cols
AS
(
    SELECT table_name, column_name, 
        ROW_NUMBER() OVER(ORDER BY table_name, column_name) AS seq, 
        ROW_NUMBER() OVER(ORDER BY table_name DESC, column_name desc) AS totrows
    FROM [INFORMATION_SCHEMA].columns
)
SELECT table_name, column_name, totrows + seq -1 as TotRows
FROM cols
WHERE seq BETWEEN @startRow AND @startRow + 49
ORDER BY seq

1 个答案:

答案 0 :(得分:1)

使用C#中的内联SQL,您唯一需要做的就是使用参数而不是局部变量。

喜欢这样。

using(SqlConnection cnn = GetAConnection())
{
    string sql = @"WITH cols
        AS
        (
        SELECT table_name, column_name, 
            ROW_NUMBER() OVER(ORDER BY table_name, column_name) AS seq, 
            ROW_NUMBER() OVER(ORDER BY table_name DESC, column_name desc) AS totrows
        FROM [INFORMATION_SCHEMA].columns
        )
        SELECT table_name, column_name, totrows + seq -1 as TotRows
        FROM cols
        WHERE seq BETWEEN @startRow AND @startRow + 49
        ORDER BY seq";

   SqlCommand cmd = new SqlCommand(sql,cnn);
   cmd.Parameters.AddWithValue("@startRow",50);

   cnn.Open();
   using(SqlDataReader rdr = cmd.ExecuteReader())
   {

         //Do something with the reader here.
   }

}