共享自定义函数 返回

IT新闻 老数据
30 11360

你们有好的Sqlfunc自义函数可以在下面贴子中发出来,不允许水贴

热忱回答30

  • PGSQL自定函数支持geometry类型查询的转换函数    


        public class PgSqlExtFunc
        {
            public static SqlFuncExternal SqlFuncExternal = new SqlFuncExternal()
            {
                UniqueMethodName = "st_astext",
                MethodValue = (expInfo, dbType, expContext) =>
                {
                  return string.Format("st_astext({0})", expInfo.Args[0].MemberName);
                }
            };
    
            public static string st_astext(string name)
            {
                throw new Exception("use lamda");
            }
        }


    0 回复
  • ?? ?? VIP0
    2020/12/23

    SQL中格式化时间为年月日

     var expMethods = new List<SqlFuncExternal>();

                expMethods.Add(new SqlFuncExternal()

                {

                    UniqueMethodName = "MyToString",

                    MethodValue = (expInfo, dbType, expContext) =>

                    {

                        if (dbType == DbType.SqlServer)

                            return string.Format("CONVERT(varchar(8),{0},112)", expInfo.Args[0].MemberName);

                        else

                            throw new Exception("未实现");

                    }

                });


    0 回复
  • -- 函数补充 , 话说本贴吧如何直接看到精华帖子啊 ?

    public static class SqlFunc2
        {
            /// <summary>
            /// 不可直接使用 , 自定義擴展入口
            /// </summary>
            /// <returns></returns>
            public static List<SqlSugar.SqlFuncExternal> MySqlFuncExternal()
            {
                List<SqlSugar.SqlFuncExternal> resultList = new List<SqlSugar.SqlFuncExternal>();
    
                resultList.Add(new SqlSugar.SqlFuncExternal
                {
                    UniqueMethodName = "GroupConcat",
                    MethodValue = (expInfo, dbType, expContext) =>
                    {
                        if (dbType == DbType.MySql)
                        {
                            return $@"group_concat( {expInfo.Args[0].MemberName} SEPARATOR ',' ) ";
                        }
                        else
                        {
                            throw new Exception("未实现");
                        }
                    }
                });
    
                return resultList;
            }
            /// <summary>
            /// 注意必須在GroupBy后使用
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="str"></param>
            /// <returns></returns>
            public static string GroupConcat<T>(T str)
            {
                throw new NotSupportedException("Can only be used in expressions");
            }
        }


    0 回复
  •     expMethods.Add(new SqlFuncExternal()
                {
                    UniqueMethodName = "ConvertTime",
                    MethodValue = (expInfo, dbType, expContext) =>
                    {
                        if (dbType == SqlSugar.DbType.MySql)
                            return $"from_unixtime({expInfo.Args[0].MemberName})";
                        else
                            throw new Exception("未实现");
                    }
                }); 
                expMethods.Add(new SqlFuncExternal()
                {
                    UniqueMethodName = "UNIX_TIMESTAMP",
                    MethodValue = (expInfo, dbType, expContext) =>
                    {
                        if (dbType == SqlSugar.DbType.MySql)
                            return $"UNIX_TIMESTAMP({expInfo.Args[0].MemberName})";
                        else
                            throw new Exception("未实现");
                    }
                });
    /// <summary>
    /// 时间戳转日期格式 此处转string为了展示方便(没有毫秒小数点)
    /// </summary>
    /// <param name="str"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static string ConvertTime<T>(T str)
    {
        //这里不能写任何实现代码,需要在上面的配置中实现
        throw new NotSupportedException("Can only be used in expressions");
    }
    /// <summary>
    /// 日期格式转时间戳
    /// </summary>
    /// <param name="str"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    /// <exception cref="NotSupportedException"></exception>
    public static long UNIX_TIMESTAMP<T>(T str)
    {
        //这里不能写任何实现代码,需要在上面的配置中实现
        throw new NotSupportedException("Can only be used in expressions");
    }


    0 回复
  •         public static string partitiondatediff(string name,DateTime? timeFiled)
            {
                //这里不能写任何实现代码,需要在上面的配置中实现
                throw new NotSupportedException("Can only be used in expressions");
            }
    
            
            private static void Test()
            {
                //Create ext method
                var expMethods = new List<SqlFuncExternal>();
                expMethods.Add(new SqlFuncExternal()
                {
                    UniqueMethodName = "partitiondatediff",
                    MethodValue = (expInfo, dbType, expContext) =>
                    {
                       return string.Format("*,ROW_NUMBER() over(partition by {0} order by abs(datediff({1}, NOW() )) )", expInfo.Args[0].MemberName, expInfo.Args[1].MemberName);
    
                    }
                });
                var db= new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.MySql,
                    ConnectionString = Config.ConnectionString,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        SqlFuncServices = expMethods//set ext method
                    }
    
                });
                db.Aop.OnLogExecuting = (sql, p) =>
                {
                    Console.WriteLine(sql);
                };
    
                db.Queryable<Order>().Select(it=> partitiondatediff(it.Name, it.CreateTime)).ToList();
    
            }

    生成的sql如下:

    SELECT *,ROW_NUMBER() over(partition by `Name` order by abs(datediff(`CreateTime`, NOW() )) ) FROM `Order`


    0 回复
  •     public static class SqlFuncExt
        {
            public static List<SqlFuncExternal> ExpMethods = new List<SqlFuncExternal>
            {
                new SqlFuncExternal()
                {
                    UniqueMethodName = "JsonContains",
                    MethodValue = (expInfo, dbType, expContext) =>
                    {
                        var value = string.Empty;
                        switch (dbType)
                        {
                            case DbType.MySql:
                                if (expInfo.Args[1].Type == typeof(string))
                                    value = $"CONCAT('\"',{expInfo.Args[1].MemberValue},'\"')";
                                else
                                    value = expInfo.Args[1].MemberValue.ToString();
                                return $" json_contains({expInfo.Args[0].MemberName}, '{value}') ";
                            case DbType.SqlServer:
                            case DbType.Sqlite:
                            case DbType.Oracle:
                            case DbType.PostgreSQL:
                            case DbType.Dm:
                            case DbType.Kdbndp:
                            case DbType.Oscar:
                            default:
                                return $" {expInfo.Args[0].MemberName} like '%{expInfo.Args[1].MemberValue}%' ";
                        }
                    }
                },
            };
    
            public static bool JsonContains<T1, T2>(T1 list, T2 value)
            {
                //这里不能写任何实现代码,需要在上面的配置中实现
                throw new NotSupportedException("Can only be used in expressions");
            }
        }

    Json的包含判断,只写了MySql


    0 回复
  • # 扩展Mysql区分大小写查询:
     var context= new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = DbType.MySqlConnector,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                    ConnectionString = RepositoryConfig.ConnectionString,
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        SqlFuncServices= new List<SqlFuncExternal>
                        {
                            new SqlFuncExternal()
                            {
                                UniqueMethodName="AbsEquals",
                                MethodValue = (expInfo, dbType, context) =>
                                {
                                    if(dbType==DbType.MySql)
                                        return $" binary {expInfo.Args[0].MemberName}='{expInfo.Args[1].MemberValue}' ";
    
                                    return $" {expInfo.Args[0].MemberName}='{expInfo.Args[1].MemberValue}' ";
                                }
                            }
                        }
                    }
                });
    
    # 使用:
    var user = context.Queryable<User>(p => SqlFuncEx.AbsEquals(p.Account, "Apricot")).FirstAsync();
    
    # 方法扩展
    public static class SqlFuncEx
    {
        public static bool AbsEquals(string first, string second)
            => throw new NotSupportedException("Can only be used in expressions");
    }


    0 回复
  • # 扩展 In 包含查询:
    var context = new SqlSugarScope(new ConnectionConfig()
    {
        DbType = DbType.MySqlConnector,
        InitKeyType = InitKeyType.Attribute,
        IsAutoCloseConnection = true,
        ConnectionString = RepositoryConfig.ConnectionString,
        ConfigureExternalServices = new ConfigureExternalServices()
        {
            SqlFuncServices = new List<SqlFuncExternal>
                        {
                            new SqlFuncExternal()
                            {
                                UniqueMethodName="In",
                                MethodValue=(methodExp, dbType, context)=>
                                {
                                    List<string> list=new List<string>();
    
                                    var @params=context?.Parameters[0]?.Value as IEnumerable<dynamic>;
                                    foreach (var key in @params ?? new object[]{})
                                    {
                                        if (key.GetType()?.IsValueType ?? false)
                                            list.Add($"{key}");
                                        else if(key.GetType()==typeof(string))
                                            list.Add($"'{key}'");
                                    }
    
                                    if(!list.Any())
                                        return $" {methodExp.Args[1].MemberName} is not null ";
    
                                   return $" {methodExp.Args[1].MemberName} in ({string.Join(',',list)}) ";
                                }
                            }
                        }
        }
    });
    
    # 查询包含数据
    var users = new List<string>
    {
        "apricot",
        "1764564459"
    };
    
    # 使用:
    var user = context.Queryable<User>(p => SqlFuncEx.In(users, p.Name)).FirstAsync();
    
    # 方法扩展
    public static class SqlFuncEx
    {
        public static bool In<T>(List<T> sources, T compare)
                => throw new NotSupportedException("Can only be used in expressions");
    }
    0 回复
  • fate sta fate sta VIP0
    2023/1/13

    @1764564459:这个功能有现成的   SqlFunc.ContainsArray

    0 回复
  • @fate sta:我试了不行,才加了一个

    0 回复
  • @fate sta:可以,现在又试了一下,这个和版本有关系么

    0 回复
  • @fate sta:现在切换原来版本是可以的,那就是使用问题,那帮忙删掉吧,以免误导大家

    0 回复
  • 子期 子期 VIP0
    2023/2/24
    public static List<SqlFuncExternal> ExpMethods = new List<SqlFuncExternal>
    {
    	new SqlFuncExternal()
    	{
    		UniqueMethodName = "SqlServerJsonArrayAny",
    		MethodValue = (expInfo, dbType, expContext) =>
    		{
    			var value = string.Empty;
    			switch (dbType)
    			{
    				case DbType.SqlServer:
    					value = string.Format("(EXISTS(SELECT * from OPENJSON({0}) WHERE [value] = {1}))"
    						, expInfo.Args[0].MemberName
    						, expInfo.Args[1].MemberName
    						);
    
    					return value ;
    				default:
    					throw new Exception("未实现");
    			}
    		}
    	},
    };
    
    public static bool SqlServerJsonArrayAny(object json, object value)
    {
    	//这里不能写任何实现代码,需要在上面的配置中实现
    	throw new NotSupportedException("Can only be used in expressions");
    }


    生的sql

    SELECT * 
    FROM tblGoodsSpecs 
    WHERE EXISTS(SELECT * FROM OPENJSON(GoodsTypeID) WHERE [value] = 5)


    是不是可以用上面的代码 整合到 SqlFunc.JsonArrayAny() 这个函数?


    0 回复
  • 子期 子期 VIP0
    2023/2/24

    Josn集合中,是否存在查询的数据

    [  
      {  
        "Order": {  
          "Number":"O43659",  
          "Date":"2011-05-31T00:00:00"  
        }
      },  
      {  
        "Order": {  
          "Number":"O43661",  
          "Date":"2011-06-01T00:00:00"  
        }
      }
    ]


    public static List<SqlFuncExternal> ExpMethods = new List<SqlFuncExternal>
    {
        new SqlFuncExternal()
        {
            UniqueMethodName = "SqlServerJsonListObjectAny",
            MethodValue = (expInfo, dbType, expContext) =>
            {
                switch (dbType)
                {
                    case DbType.SqlServer:
                        return $"(EXISTS (SELECT * from OPENJSON({expInfo.Args[0].MemberName}) " +
                            $"WITH([value] NVARCHAR(MAX) '$.{expInfo.Args[1].MemberValue.ToString().ToSqlFilter()}') " +
                            $"WHERE [value] = {expInfo.Args[2].MemberName}))";
                    default:
                        throw new Exception("未实现");
                }
            }
        },
    };
     
    public static bool SqlServerJsonListObjectAny(object json, object key, object value)
    {
        //这里不能写任何实现代码,需要在上面的配置中实现
        throw new NotSupportedException("Can only be used in expressions");
    }


    使用

    .Where(it => SqlServerJsonListObjectAny(it.vJson, "Order.Number", "O43661"))


    生产的sql

    SELECT * 
    FROM [Orders]  
    WHERE (EXISTS (SELECT * from OPENJSON([vJson]) WITH([value] NVARCHAR(MAX) '$.Order.Number') WHERE [value] = 'O43661'))


    是不是可以用上面的代码 整合到 SqlFunc.JsonListObjectAny() 这个函数?



    0 回复
  • King King VIP0
    2023/3/25
    //实现Oracle的JsonField扩展函数
    public class SqlFuncExDemo
    {
        public static SqlSugarClient SqlFuncExGetDb()
        {
            //Create ext method
            var expMethods = new List<SqlFuncExternal>();
            expMethods.Add(new SqlFuncExternal()
            {
                UniqueMethodName = nameof(JsonField),
                MethodValue = (expInfo, dbType, expContext) =>
                {
                    if (dbType == DbType.Oracle)
                        return $"JSON_VALUE({expInfo.Args[0].MemberName}, '$.{expInfo.Args[1].MemberValue.ToString().ToSqlFilter()}')";//"JSON_VALUE(j.kingorder, '$.Id') = '1'";
                    else
                        throw new Exception("未实现");
                }
            });
    
    
            var config = new ConnectionConfig()
            {
                ConnectionString = "Oracle数据库连接字符串",
                DbType = DbType.Oracle,
                IsAutoCloseConnection = true,
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    SqlFuncServices = expMethods//set ext method
                }
            };
    
            SqlSugarClient db = new SqlSugarClient(config);
            return db;
        }
    
        public static string JsonField(object json, string fieldName)
        {
            //这里不能写任何实现代码,需要在上面的配置中实现
            throw new NotSupportedException("Can only be used in expressions");
        }
    
        public static void Init()
        {
            var db = SqlFuncExGetDb();
    
            var listJson = db.Queryable<KingJsonTest>()
                            .Where(j => SqlFuncExDemo.JsonField(j.KingOrder, "Id") == "1").ToList();
    
            //生成的Sql:JSON_VALUE(字段名, '$.Json字段名') = '1'
        }
    }


    0 回复
  • 我添加了这样一个类,使用的时候报错: 当前表达式GetWeek(s1.CreatedTime.ToString()) 不支持,查看导航是否配置正确等。

    请教一下正确的使用方式应该是怎样的?

    /// <summary>
        /// 扩展函数
        /// </summary>
        public static class SqlSugarExternal
        {
            public static void SqlFuncExGetDb()
            {
                #region 获取周
                var expMethods = new List<SqlFuncExternal>();
                expMethods.Add(new SqlFuncExternal()
                {
                    UniqueMethodName = nameof(GetWeek),
                    MethodValue = (expInfo, dbType, expContext) =>
                    {
                        switch (dbType)
                        {
                            case DbType.SqlServer:
                                return string.Format("DATEPART(WEEK, {0})", expInfo.Args[0].MemberName.ToString());
                            case DbType.MySql:
                                return $"WEEK({expInfo.Args[0].MemberName.ToString()})";
                            default:
                                throw new Exception("未实现");
                        }
                    }
                });
                #endregion
    
    
            }
    
            #region 获取周
            public static string GetWeek(string fieldName)
            {
                //这里不能写任何实现代码,需要在上面的配置中实现
                throw new NotSupportedException("Can only be used in expressions");
            }
            #endregion


        

    在接口中使用,片段:

    var group = queryable_group_PercentOfPass
                        .GroupBy((s1, s2, s3, s4) => new
                        {
                            s1.LineID,
                            s2.CarId,
                            s3.IPAddress,
                            s1.BoltID,
                            s1.BoltCode,
                            s2.AssemblyContent,
                            s4.Model,
                            s2.Section,
                            s4.TypeName,
                            Week = SqlSugarExternal.GetWeek(s1.CreatedTime.ToString())
                        })
                    .HavingIF(input.LineID != null, (s1, s2, s3, s4) => s1.LineID == input.LineID)
                    .Select((s1, s2, s3, s4) => new AnalysisDataBoltPercentOfPass()
                    {
                        TotalCount = SqlFunc.AggregateCount(s1.BoltID),
                        OKCount = SqlFunc.AggregateSum(SqlFunc.IIF(s1.IsOK == true, 1, 0)),
                        NOKCount = SqlFunc.AggregateSum(SqlFunc.IIF(s1.IsOK == false, 1, 0)),
                        OKPercent = SqlFunc.Round(SqlFunc.ToDecimal(SqlFunc.AggregateSum(SqlFunc.IIF(s1.IsOK == true, 1, 0))) / SqlFunc.ToDecimal(SqlFunc.AggregateCount(s1.BoltID)), 2),
                        NOKPercent = SqlFunc.Round(SqlFunc.ToDecimal(SqlFunc.AggregateSum(SqlFunc.IIF(s1.IsOK == false, 1, 0))) / SqlFunc.ToDecimal(SqlFunc.AggregateCount(s1.BoltID)), 2),
                        IpAddress = s3.IPAddress ?? "",
                        LineID = s1.LineID,
                        CarId = s2.CarId,
                        BoltID = s1.BoltID ?? "",
                        BoltCode = s1.BoltCode ?? "",
                        Section = s2.Section ?? "",
                        ToolCategory = s4.TypeName ?? "",
                        GunModel = s4.Model ?? "",
                        AssemblyContent = s2.AssemblyContent ?? "",
                        CreatedTimeText = SqlSugarExternal.GetWeek(s1.CreatedTime.ToString())
                    })



    0 回复
  • 自由 自由 VIP0
    2023/11/7
    SELECT  "Year" AS "Year" , "Month" AS "Month" , "Day" AS "Day" , "Hour" AS "Hour" , COUNT ( "ExtensionId" ) FILTER ( WHERE "Action"  = True ) AS "ExtensionActionCount" , COUNT ( "ExtensionId" ) FILTER ( WHERE "Action"  = False ) AS "ExtensionNotActionCount"  FROM "Fcom_Huihu_V1_ExtensionActionRecord"  WHERE ( "DeleteFlag" = 0 )GROUP BY "Hour","Month","Year","Day" ORDER BY "Hour" ASC
    	public static int CountWhere<T, T2>(T field, T2 where, object whereValue)
    	{
    		//这里不能写任何实现代码,需要在上面的配置中实现
    		throw new NotSupportedException("Can only be used in expressions");
    	}
    
    	public static List<SqlFuncExternal> InitFunc()
    	{
    		var expMethods = new List<SqlFuncExternal>();
    		expMethods.Add(new SqlFuncExternal()
    		{
    			UniqueMethodName = "CountWhere",
    			MethodValue = (expInfo, dbType, expContext) =>
    			{
    				if (dbType == DbType.PostgreSQL)
    				{
    					var value = "";
    				
    
    					if (expInfo.BaseExpression.Type==typeof(string))
    					{
    						value = $"'{expInfo.Args[2].MemberValue}'";
    					}
    					else if (expInfo.BaseExpression.Type == typeof(int)|| expInfo.BaseExpression.Type == typeof(int?))
    					{
    						value = $"{expInfo.Args[2].MemberValue}";
    					}
    					else if (expInfo.BaseExpression.Type == typeof(bool) || expInfo.BaseExpression.Type == typeof(bool?))
    					{
    						value = $"{expInfo.Args[2].MemberValue}";
    					}
    					else if (expInfo.BaseExpression.Type == typeof(Guid) || expInfo.BaseExpression.Type == typeof(Guid?))
    					{
    						value = $"'{expInfo.Args[2].MemberValue}'";
    					}
    					else if (expInfo.BaseExpression.Type == typeof(long) || expInfo.BaseExpression.Type == typeof(long?))
    					{
    						value = $"{expInfo.Args[2].MemberValue}";
    					}
    					else if (expInfo.BaseExpression.Type == typeof(DateTime) || expInfo.BaseExpression.Type == typeof(DateTime?))
    					{
    						value = $"'{expInfo.Args[2].MemberValue}'";
    					}
    
    					return @$"COUNT ( {expInfo.Args[0].MemberName} ) FILTER ( WHERE {expInfo.Args[1].MemberName}  = {value} )";
    				}
    				//return string.Format("CAST({0} AS VARCHAR(MAX))", expInfo.Args[0].MemberName);
    				else
    					throw new Exception("该类型数据库未实现CountWhere");
    			}
    		});
    
    		return expMethods;
    	}
    		var list = queryDb
    			.GroupBy(ear => new { ear.Hour, ear.Month, ear.Year, ear.Day })
    			.OrderBy(ear => ear.Hour)
    			.Select(ear => new RspExtensionDayActionList
    			{
    				Year = ear.Year,
    				Month = ear.Month,
    				Day = ear.Day,
    				Hour = ear.Hour,
    				ExtensionActionCount = SqlFuncExpand.CountWhere(ear.ExtensionId, ear.Action, true),
    				ExtensionNotActionCount = SqlFuncExpand.CountWhere(ear.ExtensionId, ear.Action, false),
    			})
    			.ToList();

    Pgsql中 Count 带where

    0 回复
  • wang2650 wang2650 VIP0
    2023/12/21

           

    oracle中转为数字类型

           public static string ChangeToNumberForOracle()

           {

               //这里不能写任何实现代码,需要在上面的配置中实现

               throw new NotSupportedException("Can only be used in expressions");

           }

     expMethods.Add(new SqlFuncExternal()

            {

                UniqueMethodName = "ChangeToNumberForOracle",

                MethodValue = (expInfo, dbType, expContext) =>

                {

                    if(dbType==SqlSugar.DbType.Oracle)

                     return string.Format("CAST({0} AS NUMBER)", expInfo.Args[0].MemberName);

                    else

                     throw new Exception("未实现");

                }

            });

     


    oracle中转为字符串类型


         public static string ChangeToStringForOracle()

         {

             //这里不能写任何实现代码,需要在上面的配置中实现

             throw new NotSupportedException("Can only be used in expressions");

         }



            expMethods.Add(new SqlFuncExternal()

            {

                UniqueMethodName = "ChangeToStringForOracle",

                MethodValue = (expInfo, dbType, expContext) =>

                {

                    if(dbType==SqlSugar.DbType.Oracle)

                     return string.Format("TO_CHAR({0} )", expInfo.Args[0].MemberName);

                    else

                     throw new Exception("未实现");

                }

            });


    0 回复
  • wang2650 wang2650 VIP0
    2023/12/21

       没测试,暂时记录下,等没问题的时候,再来改。 

       希望将来有官方的出来。


    主要是为了解决,当使用oracle的时候,  数据库字段是number(38,0 )            number(38,8)   这种情况。


    因为c#中,没有对应这么大的数值类型。版主的建议是实体类用字符串类型来对应数据库的number(38,0 ) 。 

    但是当进行条件比较的时候,因为实体类是字符串,不好比较大小。 所以写了这个扩展。    

      --------只针对数值类型。---------------


     /// <summary>

        /// 数字等于

        /// </summary>

        /// <returns></returns>

        /// <exception cref="NotSupportedException"></exception>

        public static string NumberEq()

        {

            //这里不能写任何实现代码,需要在上面的配置中实现

            throw new NotSupportedException("Can only be used in expressions");

        }


        /// <summary>

        /// 数字大于

        /// </summary>

        /// <returns></returns>

        /// <exception cref="NotSupportedException"></exception>

        public static string NumberGt()

        {

            //这里不能写任何实现代码,需要在上面的配置中实现

            throw new NotSupportedException("Can only be used in expressions");

        }


        /// <summary>

        /// 数字大于等于

        /// </summary>

        /// <returns></returns>

        /// <exception cref="NotSupportedException"></exception>

        public static string NumberGE()

        {

            //这里不能写任何实现代码,需要在上面的配置中实现

            throw new NotSupportedException("Can only be used in expressions");

        }


        /// <summary>

        /// 数字小于

        /// </summary>

        /// <returns></returns>

        /// <exception cref="NotSupportedException"></exception>

        public static string NumberLs()

        {

            //这里不能写任何实现代码,需要在上面的配置中实现

            throw new NotSupportedException("Can only be used in expressions");

        }


        /// <summary>

        /// 数字小于等于

        /// </summary>

        /// <returns></returns>

        /// <exception cref="NotSupportedException"></exception>

        public static string NumberLE()

        {

            //这里不能写任何实现代码,需要在上面的配置中实现

            throw new NotSupportedException("Can only be used in expressions");

        }




           

                expMethods.Add(new SqlFuncExternal()

                {

                    UniqueMethodName = "NumberGt",

                    MethodValue = (expInfo, dbType, expContext) =>

                    {

                        if(dbType==SqlSugar.DbType.Oracle)

                         return string.Format("    {0}>{1}     ", expInfo.Args[0].MemberName,  expInfo.Args[0].MemberValue);

                        else

                         throw new Exception("未实现");

                    }

                });


                

                expMethods.Add(new SqlFuncExternal()

                {

                    UniqueMethodName = "NumberGE",

                    MethodValue = (expInfo, dbType, expContext) =>

                    {

                        if(dbType==SqlSugar.DbType.Oracle)

                         return string.Format("    {0}>={1}     ", expInfo.Args[0].MemberName,  expInfo.Args[0].MemberValue);

                        else

                         throw new Exception("未实现");

                    }

                });



                

                expMethods.Add(new SqlFuncExternal()

                {

                    UniqueMethodName = "NumberLs",

                    MethodValue = (expInfo, dbType, expContext) =>

                    {

                        if(dbType==SqlSugar.DbType.Oracle)

                         return string.Format("    {0}<{1}     ", expInfo.Args[0].MemberName,  expInfo.Args[0].MemberValue);

                        else

                         throw new Exception("未实现");

                    }

                });


                

                expMethods.Add(new SqlFuncExternal()

                {

                    UniqueMethodName = "NumberLE",

                    MethodValue = (expInfo, dbType, expContext) =>

                    {

                        if(dbType==SqlSugar.DbType.Oracle)

                         return string.Format("    {0}<={1}     ", expInfo.Args[0].MemberName,  expInfo.Args[0].MemberValue);

                        else

                         throw new Exception("未实现");

                    }

                });







    0 回复
  • fate sta fate sta VIP0
    2023/12/21

    NumberGE 这个方法是有的

    0 回复
  • fate sta fate sta VIP0
    2023/12/21

    @wang2650

    0 回复
  • fate sta fate sta VIP0
    2023/12/21

    SqlFunc.GreaterThanOrEqual 有一套这样的方法参数是object

    0 回复
  • wang2650 wang2650 VIP0
    2023/12/21

    @fate sta:  好的 。我先看看。  我很少用到扩展函数。

    0 回复
  • wang2650 wang2650 VIP0
    2023/12/21

    @fate sta

    GreaterThan有问题啊。

    MATERIALSOFINID 是数字类型

    SqlFunc.GreaterThan(it.MATERIALSOFINID,"54646546548798746546546897")


    生成的sql  这样的。     ("MATERIALSOFINID" > N'789987456123654123')   把数字转换成了字符串是有问题的。虽然能执行,但结果应该不对, 应该是  ("MATERIALSOFINID" > 789987456123654123)  才对。


    而如果 SqlFunc.GreaterThan(it.MATERIALSOFINID,54646546548798746546546897)   c# 会提示整数常量太大。


    是我用的姿势不对吗?  还是我需要自己搞自己的扩展方法,来生成   "MATERIALSOFINID" > 789987456123654123 这样的语句。




    下面是知乎中,关于oracle中 数字和字符串的比较说明


    Oracle中字符串大小比较以及数据隐式转化 - 知乎 (zhihu.com)


     select * from users where age > ’30’


      当30加上单引号,其实就变成了两个字符串之间比较大小了。


      假如有一条age的值为4,当数据库将’4’和’30’来比较大小的时候,第一步会用空格补全位数,实际比较的是’4 ’和’30’,然后从左至右依次比较ascii码大小,4的ascii码是52,3的ascii码是51,所以’4’就比’30’大了,也就出现在我们的筛选结果中了。


      如果比较的是’3’和’30’,同样的也会先去补全位数,第一位都是3然后比较第二位,第二位空格的ascii码32,0的ascii码是48,因此’3’就比’30’小了,好像没毛病,不过我们得明白其中的道理。





    0 回复
  • 我写了一些MYSQL8.0的JSON函数,方法比较多分享在GitHub了,SqlSugar Mysql JSON Functions (github.com)

    0 回复