如何使用like语句在SQL Server 2008中实现分页

时间:2016-09-02 16:30:23

标签: sql-server sql-server-2008 pagination

我对分页结果的查询是

SELECT
    *
FROM 
    (SELECT
         ROW_NUMBER() OVER (ORDER BY Id DESC) AS RowNum,
         *
     FROM 
         My_Table) AS RowConstrainedResult
WHERE 
    (RowNum >= 1 AND RowNum <= 10)
ORDER BY 
    RowNum

这很好用。但是,当我尝试使用like语句搜索结果时,它不起作用。

搜索查询

SELECT
    *
FROM 
    (SELECT
         ROW_NUMBER() OVER (ORDER BY Id DESC) AS RowNum,
         *
     FROM 
         My_Table) AS RowConstrainedResult
WHERE 
    column1 LIKE '%search%'
    AND (RowNum >= 1 AND RowNum <= 10)
ORDER BY 
    RowNum

如果前10行不包含搜索值,则返回0结果而不是查找完整表。我不能使用offset和fetch,因为它在SQL Server 2008中不支持。

用于分页的更好方法,适用于SQL Server 2008中的正常和正常

由于

1 个答案:

答案 0 :(得分:1)

你真的很接近..我用CTE过滤,然后从中选择10行。

;WITH X AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY Id DESC) AS RowNum, *
    FROM My_Table 
    WHERE column1 LIKE '%search%'
)

SELECT *
FROM X
WHERE RowNum BETWEEN 1 AND 10
ORDER BY RowNum

根据您的情况,您可以简单地逃脱:

SELECT TOP 10 *,  ROW_NUMBER() OVER (ORDER BY Id DESC) AS RowNum
FROM My_Table 
WHERE column1 LIKE '%search%'
ORDER BY RowNum