-1

Following SQL sentence throws an error on ORDER BY + LIMIT syntax so, if I remove LIMIT, works properly. Is there any syntax error or how to add LIMIT?

SELECT * FROM dbo.T0

WHERE id < (
  SELECT ISNULL((SELECT a.id FROM dbo.T0 a, dbo.T0 b, dbo.T0 c 
  WHERE 
    (a.id = b.id + 1 AND a.var1 != b.var1) 
  AND 
    c.id < a.id
  AND 
    c.timeD = '2015/08/10 18:38:00'
  AND
    c.var1 = 2
  ORDER BY a.id LIMIT 1), (SELECT MAX(id) + 1 FROM dbo.T0)))
...
jarlh
  • 42,561
  • 8
  • 45
  • 63
Jaume
  • 3,672
  • 19
  • 60
  • 119

1 Answers1

0

There's no LIMIT in sql server.

You can use a Select top 1 *, but in your case I would rather use row_number and Common table expressions (cte).

So (with some join syntax also)

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
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122