简体   繁体   中英

How to get YEAR from a DATETIME using DATEPART in HQL

I'm new user in StackOverflow, and I need a help in a HQL string..

In SQL my query is something like this..

SELECT DISTINCT DATEPART(yyyy, Moment) AS Year,
FROM PRODUCT_SOURCE

How can I convert this to HQL?

I've tried this, but didn't work..

query = "SELECT DISTINCT DATEPART(year, p.Moment) as Year, " + 
        "FROM Product_Source as p";

I am basing this on SQL2008 dialect so change as you see fit.

 
 
 
  
  public class MsSql2008ExtendedDialect : MsSql2008Dialect { public MsSql2008ExtendedDialect() { RegisterFunction("DATEPART_YEAR", new SQLFunctionTemplate(NHibernateUtil.DateTime, "datepart(year, ?1)")); } }
 
  

And to use you would use your HQL like this

 
 
 
  
  query = "SELECT DISTINCT DATEPART_YEAR(p.Moment) as Year, " + "FROM Product_Source as p";
 
  

Edit As Diego quite righly points out most of the functions in MSSQL server are already registered. For a full list see https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate/Dialect/MsSql2000Dialect.cs

So just use:-

 query = "SELECT DISTINCT year(p.Moment) as Year, " + "FROM Product_Source as p"; 

The year function is already mapped internally, so:

SELECT DISTINCT year(p.Moment) as Year,
FROM Product_Source as p

This is registered by the MsSql2000Dialect (from which newer MSSQL dialects inherit).

Now, this assumes Product_Source is the name of your class, which is odd, as it doesn't follow the usual .NET conventions (you should drop the underscore)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM