HQL - setFirstResult generates invalid SQL when CAST is used in HQL (or JPQL) on SQLServer2008Dialect

Description

Using setFirstResult (for paging) when CAST is used in HQL generates invalid SQL.
The AS part of the CAST command is treated as if it were an alias and the whole part right to it is treated as the column name i.e. "varchar(255)) as col_0_0_" instead of "col_0_0_"

SQL server then responds with:
'varchar' is not a recognized built-in function name

JPQL query:
SELECT
NEW DocumentResults
(
CAST(dok.brojDokumenta AS string) AS dokument
,dok.dokumentiID
)
FROM
pos.LC302_Dokumenti dok

Generated Hibernate query:
WITH query AS (
SELECT
inner_query.*,
ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as _hibernate_row_nr_
FROM (
select TOP
cast(lc302_doku6_.redniBrojStavke as varchar(255)) as col_0_0_,
lc302_doku6_.dokumentiID as col_1_0_
from
LC302_Dokumenti lc302_doku6_
order by
lc302_doku6_.dokumentiID DESC ) inner_query )
SELECT
varchar(255)) as col_0_0_,
col_1_0_
FROM
query
WHERE
_hibernate_row_nr_ >= ?
AND _hibernate_row_nr_ < ?

With Hibernate 4.0.1 everything works correctly.

Environment

Hibernate 4.1.8.Final, MSSQL 2008R2, SQLServer2008Dialect

Status

Assignee

Lukasz Antoniak

Reporter

Vedran Mikulcic

Fix versions

Labels

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Components

Affects versions

4.1.8

Priority

Critical