SQL查詢使用的IN條件字段很多的時候,會造成SQL語句很長,大概SQL語句不能超過8K個字符,也有說IN不能超過1000個條件,總之太長了不行,需要拆分條件分批處理。下面提供一個將Int類型的條件字段值進行字符串拼接的方法。看代碼:
class Program { static void Main(string[] args) { int[] source = { 1,2,3,4,5,6,7,8,9,10}; ShowSource(source); List<string> list = BatchJoinArray2String(source, 5).ToList(); ShowList(list); List<string> list2 = BatchJoinArray2String(source, 3).ToList(); ShowList(list2); Console.Read(); } static void ShowSource(int[] source) { string sourceStr = string.Join(",", source); Console.WriteLine("Source Arrar:{0}", sourceStr); } static void ShowList(List<string> lst) { foreach (string item in lst) Console.WriteLine("\""+item+"\""); Console.WriteLine("--------------------"); } static IEnumerable<string> BatchJoinArray2String(int[] arrSource,int batchSize) { if (batchSize <= 1) throw new ArgumentOutOfRangeException("batchSize 批處理大小不能小於1"); if (arrSource.Length > batchSize) { int[] arr10 = new int[batchSize]; int j = 0; for (int i = 0; i < arrSource.Length; i++) { if (j < batchSize) { arr10[j++] = arrSource[i]; } else { j = 0; string str = string.Join(",", arr10); arr10[j++] = arrSource[i]; yield return str; } } if (j > 0) //還有剩余 { int[] arr0 = new int[j]; Array.Copy(arr10, arr0, j); string str = string.Join(",", arr0); yield return str; } } else { string str = string.Join(",", arrSource); yield return str; } } }
運行這個示例程序,得到下面輸出:
Source Arrar:1,2,3,4,5,6,7,8,9,10 "1,2,3,4,5" "6,7,8,9,10" -------------------- "1,2,3" "4,5,6" "7,8,9" "10" --------------------
在你的程序中,可以像下面這樣使用:
string sql_update=@" update t2 set AA =1 , BB ='2222' FROM [MyTable] as t2 WHERE t2.[ID] in ( @IDs ); "; //每次更新50條記錄 using (SqlConnection conn = new SqlConnection(DefaultConnectionString)) { conn.Open(); foreach (string ids in BatchJoinArray2String(XXXIds.ToArray(), 50)) { string sql = sql_update.Replace("@IDs", ids); SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql); } conn.Close(); }
該功能將集成在SOD框架中,敬請期待。