0

I need to execute native sqn on nhibernate and get sum from complex query needed for reporting. The sql query returns only one float value for a sum.

float theSum= session.CreateSQLQuery(@"select sum(myfield) myfield from ....")
                               .AddScalar("myfield", NHibernateUtil.Single)
                               .UniqueResult<float>();

Is this OK ?
Is there any other way to do this ? I guess this auto casts null value to 0.

darpet
  • 3,073
  • 3
  • 33
  • 40
  • The code you show won't even compile, Ignoring the missing quote, the SQL syntax is incorrect. You should use nullable float as return type if the query can yield null. Even ignoring that, are you having some actual problem? The question you state is very open-ended. – Oskar Berggren Jan 06 '13 at 07:33
  • Of course the sql syntax is incorrect because it is part of the sql. The rest if the sql is not shown because of the complexity, and it does not matter for the answer. Did you not see the "..." at the end of the sql ?. By the way, it compiles and works (you have not tried this in the compiler!), and if the value of the sum is null, it casts it to 0, so no nullable. I did not found your comment helpful. The question is straight. Is the solution ok and are there better approaches and how. – darpet Jan 06 '13 at 14:30
  • Well, after you've edited it I would agree that it compiles. It was not the ... I referred to either, but what I did refer to was in fact something I misread, so it's still my bad. – Oskar Berggren Jan 06 '13 at 16:32
  • Double quotes at the end were typing mistake, but it was obvious :) – darpet Jan 06 '13 at 19:13

1 Answers1

0

I've double checked the code, and it does contain an explicit conversion of null to 0 - you should use <float?> if you want to see/act on the difference between 0 and null.

You might also want to look at named queries as an alternative: http://nhibernate.info/doc/nh/en/index.html#querysql-namedqueries

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
Oskar Berggren
  • 5,583
  • 1
  • 19
  • 36