NHibernate 下 执行SQL语句 (原创)

public IList ExecuteSQLQuery(string sql) {
            ITransaction trn = this._session.BeginTransaction();
            try {
                ISQLQuery sqlQuery = _session.CreateSQLQuery(sql);

                int ss = sql.IndexOf(" ");
                sql = sql.Substring(ss + 1);
                int ee = sql.IndexOf(" from");
                sql = sql.Substring(0, ee);
                string[] filed = sql.Split(new char[] { ',' });
                for (int i = 0; i < filed.Length; i++) {
                    if (filed[i].IndexOf("as") > 0) {
                        filed[i] = filed[i].Substring(filed[i].IndexOf("as") + 3).Trim();
                    }
                    sqlQuery.AddScalar(filed[i], NHibernateUtil.String);
                }
                IList resultList = sqlQuery.List();
                trn.Commit();
                return resultList;
            } catch (Exception e) {
                trn.Rollback();
                throw e;
            }
        }


注意,此方法 的SQLSTR最好 字段和表明 都用别名,例如:select t1.filed1 as filed1,t1.field2 as field2 from table1 as t1 where t1.filed2>0;

posted @ 2008-06-04 13:39  acme  阅读(386)  评论(0编辑  收藏  举报