Question

I want to make use of the Convert function in SQL Server 2008 so I can search on a DateTime column.

The proposed SQL would look something like this:

SELECT (list of fields) FROM aTable
WHERE CONVERT(VARCHAR(25), theColumn) LIKE '%2009%'

Here is part of the criteria that tries to emulate the call to convert:

Projections.SqlFunction("CONVERT", 
  NHibernateUtil.String, 
  Projections.Constant("varchar(25)"), 
  Projections.Property(searchCol))

The search column would be dynamically selected so it cannot be hard coded in a query.

The problem is that when the SQL is generated by nhibernate, its passing in the data type as a string, when there shouldn't be any quotes around it.

So the generated sql looks like:

(convert(@p3, this_.theColumn) LIKE @p4

When it needs to be:

(convert(varchar(25), this_.theColumn) LIKE @p4

I am definitely sure the problem is with Projections.Constant("varchar(25)") but I do not know the correct projections syntax to make it work.

Was it helpful?

Solution

If you could accept the CAST instead of CONVERT (And I am almost sure that you can), then there is more straightforward solution.

Instead of calling "SQL Server related" function, let's call the abstraction, which should be working on most DB Servers (based on supported NHibernate dilacts)

Projections.Cast(NHibernateUtil.String, Projections.Property(searchCol))

So the Restriction used in a WHERE clause could look like this:

Restrictions
    .Like (
        Projections.Cast(NHibernateUtil.String, Projections.Property(searchCol))
        , "2009"
        , MatchMode.Anywhere
    )

And the result generated by NHibernate, using the SQL Server dialect would be:

WHERE cast( this_.theColumn as NVARCHAR(255)) like @p1 ... @p1=N'%2009%'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top