0

我对使用 MSSQL 还很陌生,遇到了一个奇怪的问题。给定最后一个查询的第一个记录 id,我需要找到之前的 50 行满足与第一个查询相同的条件并按降序返回它们。这是针对 ASP.NET 站点的,我很确定 ASP 端是正确的,但是当我尝试运行 SQL 查询时它给出了错误的结果

这是我一直在尝试的 SQL

 WITH PreviousPosts AS 
 (
    SELECT *
    FROM [database].[dbo].[table]
    WHERE (A_1STNAME LIKE '(variable)%')
    AND A_RECID < '(lastPost)'
 )
SELECT TOP 50 * FROM PreviousPosts
ORDER BY A_RECID ASC

其中“(变量)”和“(lastPost)”实际上是用我的C#填充的正确参数

我不再收到错误,但现在无论提供什么作为 lastPost,我都会得到相同的结果。

更新:结果是表中的前 50 个名字,例如(在我的测试用例中)“James”

任何帮助表示赞赏:)

4

4 回答 4

4

您在 CTE 中缺少表名。看**[TABLENAME]**

 WITH PreviousPosts AS 
 (
    SELECT *
    FROM [database].[dbo].**[TABLENAME]**
    WHERE (A_1STNAME LIKE (variable)%)
    AND A_RECID < (lastPost)
    ORDER BY A_RECID DESC
 )
SELECT TOP 50 * FROM PreviousPosts
ORDER BY A_RECID ASC
于 2012-04-06T18:41:05.027 回答
2

如前所述,您在 CTE 中缺少表名。您还缺少要从 CTE 中获取的列。

你应该改变:

SELECT TOP 50 FROM PreviousPosts ORDER BY A_RECID ASC

到:

SELECT TOP 50 * FROM PreviousPosts ORDER BY A_RECID ASC
于 2012-04-06T18:45:20.803 回答
0

要添加到列表中,您不能在 CTE 中进行排序。为了得到你想要的,完全放弃 CTE:

SELECT top 50 * 
FROM [database].[dbo].**[TABLENAME]** 
WHERE (A_1STNAME LIKE (variable)%) 
AND A_RECID < (lastPost) 
ORDER BY A_RECID DESC 
于 2012-04-06T18:48:35.027 回答
0

这是一个尝试,我现在知道你的架构。我仍然不得不做出比我能接受的更多的假设,所以这可能不是正确的:

;WITH RankedRecords AS
(
    SELECT
        ROW_NUMBER() OVER(ORDER BY A_RECID DESC) Row
        , A_RECID
    FROM [database]..[table]
    WHERE A_1STNAME LIKE '(variable)%')
        AND CAST(LEFT(A_RECID, 8) AS DATE) < CAST(LEFT('(lastPost)', 8) AS DATE)
)
SELECT TOP 50
    T.*
FROM[database]..[table] T
INNER JOIN RankedRecords
    ON RankedRecords.A_RECID = T.A_RECID
    AND RankedRecords BETWEEN (@LastPost - 51) AND (@LastPost - 1)
ORDER BY RankedRecords.Row
于 2012-04-06T19:48:15.637 回答