Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hitting the 2100 parameter limit (SQL Server) when using Contains()

from f in CUSTOMERS where depts.Contains(f.DEPT_ID) select f.NAME 

depts is a list (IEnumerable<int>) of department ids

This query works fine until you pass a large list (say around 3000 dept ids) .. then I get this error:

The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Too many parameters were provided in this RPC request. The maximum is 2100.

I changed my query to:

var dept_ids = string.Join(" ", depts.ToStringArray()); from f in CUSTOMERS where dept_ids.IndexOf(Convert.ToString(f.DEPT_id)) != -1 select f.NAME 

using IndexOf() fixed the error but made the query slow. Is there any other way to solve this? thanks so much.

like image 719
ban-G Avatar asked Mar 17 '09 21:03

ban-G


People also ask

How many parameters SQL command contains?

Microsoft SQL Server has a limit on the number of parameters that a parameterized query can have (2100).

How do I increase SQL limit?

Tools>>Configure>>System Settings>>Display tab. Increase the number for "Maximum number of records shown in SQL Query results:" Click OK. Test.

Is there a limit to a where clause SQL?

The maximum number of clauses in a WHERE clause is 40.

How do you limit the number of records to return from a query?

The SQL SELECT TOP Clause The SELECT TOP clause is used to specify the number of records to return. The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance. Note: Not all database systems support the SELECT TOP clause.


2 Answers

My solution (Guids is a list of ids you would like to filter by):

List<MyTestEntity> result = new List<MyTestEntity>(); for(int i = 0; i < Math.Ceiling((double)Guids.Count / 2000); i++) {     var nextGuids = Guids.Skip(i * 2000).Take(2000);     result.AddRange(db.Tests.Where(x => nextGuids.Contains(x.Id))); } this.DataContext = result; 
like image 113
ADM-IT Avatar answered Oct 11 '22 11:10

ADM-IT


Why not write the query in sql and attach your entity?

It's been awhile since I worked in Linq, but here goes:

IQuery q = Session.CreateQuery(@"          select *           from customerTable f          where f.DEPT_id in (" + string.Join(",", depts.ToStringArray()) + ")"); q.AttachEntity(CUSTOMER); 

Of course, you will need to protect against injection, but that shouldn't be too hard.

like image 39
Joel Avatar answered Oct 11 '22 10:10

Joel