示例#1
0
        public string QuerySqlBuild(IQueryParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("参数集合不能为null");
            }

            string sql;

            //分页查询
            if (_queryBody.Take > 0)
            {
                var select = ResolveSelect();
                var from   = ResolveFrom(parameters);
                var where = ResolveWhere(parameters);
                var sort = ResolveOrder();

                #region ==SqlServer分页需要指定排序==

                //SqlServer分页需要指定排序,此处判断是否有主键,有主键默认按照主键排序
                if (_sqlAdapter.SqlDialect == SqlDialect.SqlServer && sort.IsNull())
                {
                    var first = _queryBody.JoinDescriptors.First();
                    if (first.EntityDescriptor.PrimaryKey.IsNo())
                    {
                        throw new Exception("SqlServer数据库没有主键的表需要指定排序字段才可以分页查询");
                    }

                    sort = _queryBody.JoinDescriptors.Count > 1 ? $"{_sqlAdapter.AppendQuote(first.Alias)}.{_sqlAdapter.AppendQuote(first.EntityDescriptor.PrimaryKey.Name)}" : first.EntityDescriptor.PrimaryKey.Name;
                }

                #endregion

                sql = _sqlAdapter.GeneratePagingSql(select, from, where, sort, _queryBody.Skip, _queryBody.Take);
            }
            else
            {
                var sqlBuilder = new StringBuilder("SELECT ");

                ResolveSelect(sqlBuilder);

                sqlBuilder.Append(" FROM ");

                ResolveFrom(sqlBuilder, parameters);

                ResolveWhere(sqlBuilder, parameters);

                ResolveOrder(sqlBuilder);

                sql = sqlBuilder.ToString();
            }

            _logger?.LogDebug("Query:{0}", sql);

            return(sql);
        }
示例#2
0
        public string ToSql()
        {
            var selectSql = _expressionResolve.ToSelectSql(_selectExpression);

            //取前几条表示分页查询
            return(_take > 0 ? _sqlAdapter.GeneratePagingSql(_descriptor.TableName, WhereSql, _skip, _take, OrderBySql(), selectSql) : $"{_sqlStatement.Query} {WhereSql} {OrderBySql()}");
        }