[英]What's the most performant way to pass a giant list of items as a parameter to SQL Server?
I have a table with millions of entries, and I'm loading data from it using a stored procedure (which applies pagination/sorting and some other things).我有一个包含数百万个条目的表,我正在使用存储过程(应用分页/排序和其他一些东西)从中加载数据。
My problem is one of the parameters I pass in is a large list of CompanyId
and EmployeeId
values.我的问题是我传入的参数之一是CompanyId
和EmployeeId
值的大列表。 These values are structured as CompanyId:EmployeeId
and the string would look like this:这些值的结构为CompanyId:EmployeeId
,字符串如下所示:
@companiesAndEmployees = 'CO5555:EM10001,CO5555:EM10002,CO5555:EM10003,CO7777:EM10004' --can by thousands of items long
CompanyId+EmployeeId
is how I can uniquely identify the employees I want to load items from the database for. CompanyId+EmployeeId
是我唯一标识要从数据库加载项目的员工的方法。 I use STRING_SPLIT()
on this list to "filter" my query for just the employees I want.我在这个列表中使用STRING_SPLIT()
来“过滤”我的查询,只针对我想要的员工。
SELECT *
FROM MyTable mt
INNER JOIN STRING_SPLIT(@companiesAndemployees, ',') ce
ON ce.value = mt.CompanyId + ':' + mt.EmployeeId
My problem is that this list of employees can theoretically be many thousands of items long, and this query begins to choke to the point where I get this SQL timeout exception:我的问题是这个员工列表理论上可以有数千个项目,并且这个查询开始阻塞到我得到这个 SQL 超时异常的地步:
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. System.Data.Entity.Core.EntityCommandExecutionException:执行命令定义时出错。 See the inner exception for details.有关详细信息,请参阅内部异常。
System.Data.SqlClient.SqlException: Execution Timeout Expired. System.Data.SqlClient.SqlException:执行超时已过期。 The timeout period elapsed prior to completion of the operation or the server is not responding.在操作完成之前超时时间已过或服务器没有响应。
System.ComponentModel.Win32Exception: System.ComponentModel.Win32Exception:
What would be the most performant way of retrieving rows only for the users I'm asking for, when there can be many thousands of them?当可能有成千上万的用户时,只为我要求的用户检索行的最高效方式是什么?
SqlBulkCopy is an extremely efficient way to get data to the SQL Server. SqlBulkCopy是将数据获取到 SQL 服务器的一种极其有效的方法。
You can use it with a temporary table, then do a SELECT
joining the temp table to MyTable
.您可以将它与临时表一起使用,然后执行SELECT
将临时表连接到MyTable
。
I'm a bit unclear if you're applying this before or after a stored procedure.我有点不清楚您是在存储过程之前还是之后应用它。 If you are doing it after, you can insert the result of the stored proc to a temp table, then join the two.如果您在之后这样做,您可以将存储过程的结果插入到临时表中,然后将两者连接起来。
If you're doing it before, and need to pass this, things get a bit sketchy, but are possible: How to pass a temp table as a parameter into a separate stored procedure如果您以前这样做,并且需要传递它,事情会变得有点粗略,但有可能:如何将临时表作为参数传递到单独的存储过程中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.