3

My databse is MS SQL. I want to use ROW_NUMBER() in HQL. Is it possible? How? I know about Custom Functions. But prefer a way that does not need to modify web.config.

UPDATE:

My final goal is to delete all records in a table/entity except than last n records with HQL. I don't like to load all of them in memory then deleting them.

Afshar Mohebi
  • 10,479
  • 17
  • 82
  • 126
  • 1
    What are you planning to do? There's always http://stackoverflow.com/questions/1998560/row-number-and-nhibernate-finding-an-items-page/2034389#2034389 , but we'd need to know your needs. – rebelliard Apr 05 '11 at 12:12
  • @binaryhowl: please seee my update. – Afshar Mohebi Apr 06 '11 at 05:11
  • That sounds like a strange goal - is this a once off? Is HQL really necessary or can you just use plain SQL (using Session.CreateSqlQuery)? – cbp Apr 06 '11 at 05:15

3 Answers3

1

as of NH v2 the HQL supports delete and update statements via IQuery.ExecuteUpdate(). You could experiment using also the IQuery.SetMaxResults() and IQuery.SetFirstResult() (which use ROW_NUMBER()) to get the desired effect.

EDIT: i experimented my self, the SetMaxResults and SetFirstResult are ignored on sql generation for ExecuteUpdate() so this will not work.

Also @ the comment below, an HQL ExecuteUpdate (and at least for DELETE) does not necessarily mean an in-memory load of object state.

Jaguar
  • 5,929
  • 34
  • 48
0

I would use plain SQL for this. Mainly because of "I don't like to load all of them in memory". This is not a very object oriented task, so you don't need an ORM.

Note: plain SQL means that the session cache gets broken. You don't get any troubles as long as you don't do other stuff within the same (non-stateless) session. If you do, I would choose the OO way and actually load the items into memory.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
0

I would use a combination of HQL's ExecuteUpdate and Desc ordering, similar to:

delete Person p1 
where p1.Id in 
            (select p2.Id 
             from Person p2 
             where rownum <= 10
             order by p2.Id desc)
rebelliard
  • 9,592
  • 6
  • 47
  • 80