Order by和Limit语法

时间:2015-08-14 09:47:49

标签: sql sql-server sql-server-2014

以下SQL语句会在+? + ORDER BY语法上引发错误,因此,如果我删除LIMIT,则会正常运行。是否存在语法错误或如何添加LIMIT

LIMIT

1 个答案:

答案 0 :(得分:0)

sql server中没有LIMIT

您可以使用Select top 1 *,但在您的情况下,我宁愿使用row_number和公用表表达式(cte)。

所以(也有一些连接语法)

with cte as (select 
             a.id, 
             row_number() over(order by a.Id) rn
             from dbo.T0 a 
             join dbo.T0 b on a.id = b.id + 1 and a.var1 != b.var1
             join dbo.T0 c on c.id < a.id
             where c.timeD = '2015/08/10 18:38:00'
             and c.var1 = 2),
     cte2 as (select id from cte where rn = 1
              union
              SELECT MAX(id) + 1 as id FROM dbo.T0)

select * from dbo.T0 where id < (select min(id) from cte2)
-- we take the min, here, 
--as we want the first part of the union of cte2 if it exists
-- and it will always be smaller then max(id) + 1