23

What is NHibernate HQL's Equivalent to T-SQL's TOP Keyword?

Also what is the non-HQL way for saying give me the first 15 of a class?

BuddyJoe
  • 69,735
  • 114
  • 291
  • 466

5 Answers5

33

It's actually pretty easy in HQL:

var top15 = session.CreateQuery("from SomeEntity")
                .SetFirstResult(0)
                .SetMaxResults(15)
                .List<SomeEntity>();

Don't know how to do this using the criteria API though.

mookid8000
  • 18,258
  • 2
  • 39
  • 63
10

Criteria API Method:

ICriteria criteria = DaoSession.CreateCriteria(typeof(T));
criteria.SetFirstResult(StartIndex);
criteria.SetMaxResults(MaximumObjects);
return criteria.List<T>();
  • 1
    MaximumObjects is just an integer variable to tell SetMaxResults how many objects to return. In your case, you could hard code 15 instead, i.e. criteria.SetMaxResults(15); –  Feb 17 '09 at 01:13
  • Haha... so in other words it is identical to CreateQuery() after the instance is created. – Andrew Burns Feb 19 '09 at 15:47
  • You can chain all of those ICriteria method calls fluently, would make it more readable. – UpTheCreek Apr 19 '11 at 08:36
4

From NHibernate 3.2 you could use SKIP n / TAKE n in hql at the end of the query. It could be very helpful in subqueries where you can not use SetMaxResults.

For example:

select l, (select u from User u where u.Location = l order by u.Date asc take 1) 
from Location l
Pavel Bakshy
  • 7,697
  • 3
  • 37
  • 22
0

For completeness, here is how to do it with the QueryOver API introduced in NHibernate 3.0:

var top15 = session.QueryOver<SomeEntity>().Take(15).List();

Throw in a .Skip(someInt) if you need to define a start index, e.g. for paging.

Jørn Schou-Rode
  • 37,718
  • 15
  • 88
  • 122
-2

mookid8000 is giving false information.

there is no way of setting SQL TOP N with HQL :(

it always downloads all of the table to .NET and the takes the TOP, wich is just plain stupid!

Andrew Rebane
  • 199
  • 3
  • 12