您的查询基本上是在强制SQLAlchemy发出具有2000多个参数(
SELECT * WHERe Y IN (list of 2000+values))的查询。不同的RDBMS(和不同的驱动程序)对您可能拥有的参数数量有限制。
尽管您的堆栈跟踪未涵盖确切的错误,但我注意到您正在使用SQL Server,并且您所谈论的数字在某些情况下可疑接近SQL
Server施加的2100参数限制(请参阅 每个用户定义的参数)功能 上此Microsoft知识库文章)。我愿意打赌,这就是您遇到的问题。
您可以采用的最简单的方法是简单地对每个查询(例如1000个项目)分批运行查询
employee_pre_list:
results = []batch_size = 1000batch_start = 0while batch_start < len(employee_pre_list): batch_end = batch_start + batch_size employee_pre_batch = employee_pre_list[batch_start:batch_end] query = session.query(TblUserEmployee, TblUser).filter( and_( (TblUser.UserId == TblUserEmployee.EmployeeId), (func.lower(TblUserEmployee.EmployeeCode).in_(employee_pre_batch)), (TblUser.OrgnId == MIG_CONSTANTS.context.organizationid), (TblUser.UserTypeId == user_type) )) results.append(query.all()) batch_start += batch_size
在此示例中,我们将创建一个空结果列表,并将每一批结果附加到该列表中。我们将批量大小设置为1000,起始位置设置为0(中的第一项
employee_pre_list)。然后,我们每1000个批次运行一次查询,并将结果追加到
results,直到中没有要查询的记录
employee_pre_list。
当然,还有其他方法,但这是一种不需要您使用其他RDBMS的方法,并且可能最容易处理到您的代码中。



