Convert an array of integers for use in a SQL “IN” clause

前端 未结 8 2178
死守一世寂寞
死守一世寂寞 2021-01-05 03:44

Surely there is a framework method that given an array of integers, strings etc converts them into a list that can be used in a SQL \"IN\" clause?

e.g.

8条回答
  •  北海茫月
    2021-01-05 04:28

    If your list of integers is large, you may end up generating a string that is too long for your database to accept. E.g. I think the maximum length of a VARCHAR in SQL2000 is around 8K.

    So I have a set of helper method something like the sample below, which return an enumeration of strings, which can then be used as follows:

    List idList = ...;
    using(SqlCommand command = ...)
    {
        ...
        foreach(string idString in ConcatenateValues(ids,",", maxLength, false))
        {
           command.Parameters[...] = idString;
           // or command.CommandText = "SELECT ... IN (" + idString + ")...";
           ... execute command ...
        }
    }
    

    The concatenate method might look something like the following:

    public static IEnumerable ConcatenateValues(IEnumerable values, string separator, int maxLength, bool skipDuplicates)
    {
        IDictionary valueDictionary = null;
        StringBuilder sb = new StringBuilder();
        if (skipDuplicates)
        {
            valueDictionary = new Dictionary();
        }
        foreach (int value in values)
        {
            if (skipDuplicates)
            {
                if (valueDictionary.ContainsKey(value)) continue;
                valueDictionary.Add(value, "");
            }
            string s = value.ToString(CultureInfo.InvariantCulture);
            if ((sb.Length + separator.Length + s.Length) > maxLength)
            {
                // Max length reached, yield the result and start again
                if (sb.Length > 0) yield return sb.ToString();
                sb.Length = 0;
            }
            if (sb.Length > 0) sb.Append(separator);
            sb.Append(s);
        }
        // Yield whatever's left over
        if (sb.Length > 0) yield return sb.ToString();
    }
    

提交回复
热议问题