SQL 查询可选的自定义分页,C# ObjectDataSource

SQL Query for Optional Custom Paging, C# ObjectDataSource

ObjectDataSource 的 SQL 自定义分页查询,允许每个请求仅提供与特定页面相关的数据,提高加载速度。

问题是如何使分页可选?

string Query = @"
   DECLARE @PagedData int
   SET @PagedData = 1

   SELECT    
        CASE 
            WHEN @PagedData = 1 
            THEN (SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY " + _sortColumns + @") AS ResultRank, *

                FROM dbTable

                WHERE (FeatureString LIKE '%gold%')

                AS ProductsWithRowNumber WHERE ResultRank > 
                " + startIndex + " AND ResultRank <= (" + startIndex + " + " + pageSize + @"))

            ELSE (SELECT * FROM dbTable WHERE (FeatureString LIKE '%gold%'))  
        END";

目标是让 SQL 函数能够只获取特定页面的数据,或者它可以关闭分页获取所有相关数据。

以上是我尝试使用CASE根据变量PagedData的值来切换查询是否分页。但是,此方法以错误结束。

如果您需要我澄清任何问题,请告诉我,谢谢。

您的 SQL 看起来不完全正确,但假设它是正确的,这里是如何使用 if 语句:

 string Query = @"
DECLARE @PagedData int
SET @PagedData = 1

IF @PagedData = 1 
(
  SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY " + _sortColumns + @") AS ResultRank, *
   FROM dbTable
   WHERE (FeatureString LIKE '%gold%')
      AS ProductsWithRowNumber WHERE ResultRank > 
   " + startIndex + " AND ResultRank <= (" + startIndex + " + " + pageSize + @")
)
ELSE 
(
  SELECT * FROM dbTable WHERE (FeatureString LIKE '%gold%')
)";

https://msdn.microsoft.com/en-us/library/ms182717.aspx