以下是我要将分页数据返回到我的网络应用以获取前100个元素的查询:
SELECT * FROM (SELECT ROWNUM AS RN, Id,DateTime FROM Schema.MyDb WHERE
Deleted='F' AND (Code>=2) AND (Type LIKE '%stock%')
ORDER BY Datetime DESC) WHERE ROWNUM <
100 AND RN > 0
这在Oracle数据库上运行得很好,但是在SQL Server 2012下运行时我收到以下错误:
Message 1033, Level 15, State 1, Server NBOOK\SQLEXPRESS, Line 1:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqu
eries, and common table expressions, unless TOP, OFFSET or FOR XML is also speci
fied.
有关如何修复此问题并使其工作而不会丢失逻辑的任何提示(最终结果需要是有序查询的100个第一行)?
感谢您的帮助。
答案 0 :(得分:3)
rownum
特定于Oracle。在SQL Server(和Oracle)中,您应该使用row_number()
代替:
SELECT *
FROM (SELECT row_number() over (order by DateTime desc) as RN, Id, DateTime
FROM Schema.MyDb
WHERE Deleted = 'F' AND (Code >= 2) AND (Type LIKE '%stock%')
) t
WHERE RN < 100 AND RN > 0;
此外,子查询需要SQL Server中的别名。以上内容适用于两个数据库。
答案 1 :(得分:1)
您的订单是在子查询中。拿出来,你应该很好。