在针对ms sql server运行更新查询时,我收到此奇怪错误 Antlr.Runtime.MismatchedTokenException 。我正在有效地尝试从另一个表的总和查询结果更新表。我尝试在sql控制台中执行sql directy,它没有任何问题。
var sql = new StringBuilder();
sql.Append("UPDATE s SET s.pokriveno = l.pokriveno,");
sql.Append("s.zatvoreno = CASE WHEN s.Pokriveno = s.Duguje + s.Potrazuje THEN 1 ELSE 0 END ");
sql.Append("FROM Stavka s ");
sql.Append("LEFT JOIN ");
sql.Append("(");
sql.Append(" SELECT id, SUM(pokriveno) pokriveno FROM ");
sql.Append(" (");
sql.Append(" SELECT l.Stavka1Id id, SUM(l.iznos1) pokriveno ");
sql.Append(" FROM Link l ");
sql.Append(" JOIN stavka s ON l.Stavka1Id = s.Id ");
sql.Append(" JOIN Dokument d ON s.DokumentId = d.id ");
sql.Append(" WHERE d.godina = :year ");
sql.Append(" GROUP BY Stavka1Id ");
sql.Append(" UNION ALL ");
sql.Append(" SELECT l.Stavka2Id id, SUM(l.iznos2) pokriveno ");
sql.Append(" FROM Link l ");
sql.Append(" JOIN stavka s ON l.Stavka2Id = s.Id ");
sql.Append(" JOIN Dokument d ON s.DokumentId = d.id ");
sql.Append(" WHERE d.godina = :year ");
sql.Append(" GROUP BY Stavka2Id ");
sql.Append(" ) tmp GROUP BY id ");
sql.Append(") l ");
sql.Append("ON s.Id = l.id");
Debug.WriteLine(sql);
var query = session.CreateQuery(sql.ToString());
query.SetParameter("year", year);
int count = query.ExecuteUpdate();
任何人都知道发生了什么?
答案 0 :(得分:2)
这里的问题是,您在传递本机SQL语句时使用API来操作HQL / DML查询。参见:
我们必须使用.CreateQuery(hql)
而不是.CreateSQLQuery(sql)
期望的hql,而是希望传递本机SQL
var query = session
//.CreateQuery(sql.ToString())
.CreateSQLQuery(sql.ToString())
;
query.SetParameter("year", year);
int count = query.ExecuteUpdate();
另请参阅CreateQuery
的用法: