C#进行IN条件查询的SQL语句使用SqlParameter的通用方法

  • 创建对象
    public class SqlParameterInfo
    {
        /// <summary>
        /// 变量字符串
        /// </summary>
        public string ParameterStr { get; set; }

        /// <summary>
        /// 参数数组
        /// </summary>
        public SqlParameter[] ParameterArr { get; set; }
    }
  • 通用方法
     /// <summary>
        /// 构建参数信息
        /// </summary>
        /// <param name="sgin">参数头名称</param>
        /// <param name="valArr">参数值数组</param>
        /// <param name="parameters">已存在的参数数组</param>
        /// <returns></returns>
        public static SqlParameterInfo BuildParameterInfoByObj<T>(string sgin, T[] valArr, SqlParameter[] parameters)
        {
            if (string.IsNullOrEmpty(sgin))
            {
                sgin = "tmpParameter" + new Random().Next(1, 100);
            }
            if (valArr==null||valArr.Length==0)
            {
                return new SqlParameterInfo() { ParameterStr = string.Empty, ParameterArr = parameters };
            }
            StringBuilder builder = new StringBuilder();
            var parameterList = new List<SqlParameter>();
            if (parameters!=null&& parameters.Length>0)
            {
                parameterList.AddRange(parameters);
            }
            for (int i = 0; i < valArr.Length; i++)
            {
                builder.Append($"@{sgin}{i},");
                parameterList.Add(new SqlParameter($"@{sgin}{i}",valArr[i]));
            }
            return new SqlParameterInfo() { ParameterStr = builder.ToString().TrimEnd(','),ParameterArr=parameterList.ToArray() };
        }
  • 调用方法Demo
        public object Test()
        {
            using (Test entities = new Test())
            {
                var parameterValArr = new object[] { "IT部", "人力资源行政部", "财务部" };
                var parameterValArr2 = new object[] { 1, 5, 6 };
                var parameterResult = MsSqlHelper.BuildParameterInfoByObj("Dep", parameterValArr, null);
                var parameterResult2 = MsSqlHelper.BuildParameterInfoByObj("Id", parameterValArr2, parameterResult.ParameterArr);
                string sql = $"SELECT DepCode,DepName FROM Test WHERE DepName IN({parameterResult.ParameterStr}) AND Id IN ({parameterResult2.ParameterStr})";
                var result = entities.Database.SqlQuery<Test>(sql, parameterResult2.ParameterArr).ToList();
                return result;
            }
        }

 

posted @ 2021-08-23 10:20  来瓶冰镇可乐吧  阅读(921)  评论(0编辑  收藏  举报