Maui Blazor 中文社区 QQ群:645660665

Freesql ORM 数据库In出现"查询处理器用尽了内部资源,无法生成查询计划...请简化查询"解决方法

批量插入或者更新商品表, 刚开始客户商品量在1万左右,用如下写法没什么大问题, 数据库还能够支持,但是到达5万+ 时候, 就会报数据库报错 内部错误: 达到了表达式服务限制。请在您的查询中查找潜在的复杂表达式,并尝试简化它们。

System.Data.SqlClient.SqlException:“查询处理器用尽了内部资源,无法生成查询计划。这种情况很少出现,只有在查询极其复杂或引用了大量表或分区时才会出现。请简化查询。如果您认为该消息的出现纯属错误,请与客户支持服务部门联系,了解详细信息。”

测试代码:

var items = new List<ProductsImport>(…);
//直接举例数据说明,真实环境是取上面的数据里面的 BarCode 列表
var barcodes = new List<string>("1","2","3","4",…);

//获取存在的商品以便批量修改
var existProducts = fsql.Select<Products>().Where(a => barcodes.Contains(a.BarCode)).ToList();

//sql:  select * from Products where BarCode in('1','2','3','4',…)

//sql:  UPDATE [Products] SET xxx WHERE ((([BarCode ]) in ('1','2','3','4',…)))

class ProductsImport{
  public string BarCode { get;set;}
}

class Products{
  public string BarCode { get;set;}

  [Navigate(nameof(BarCode))]
  public virtual ProductsImport ProductsImports { get; set; }
}

请教了一下叶老板, 说用临时表 SqlBulkCopy , 再 innerjoin 查询数据, 那就恶补一下试试看吧.

最后代码如下:

var items = new List<ProductsImport>(…);

//创建临时表,比较数据
var tempTable = $"ProductsImport_{Guid.NewGuid().ToString("N")}";
fsql.CodeFirst.SyncStructure(typeof(ProductsImport), tempTable);
fsql.Insert<ProductsImport>().AsTable(tempTable).AppendData(items).ExecuteSqlBulkCopy();

//获取存在的商品以便批量修改
var existProducts = fsql.Select<Products>().
  InnerJoin(a => a.BarCode == a.ProductsImports.BarCode).
  AsTable((type, oldname) => type == typeof(ProductsImport) ? tempTable : oldname).
  ToList();

//Do something
...

//最后把临时表清掉
fsql.Delete<ProductsImport>().AsTable(tempTable).Where(a => 1 == 1).ExecuteAffrows();

posted @ 2023-03-13 03:05  AlexChow  阅读(431)  评论(0编辑  收藏  举报