共享自定义函数 返回

IT新闻
19 6354

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

热忱回答19

  • 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 回复
  • 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 回复
  • 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 回复