我正在使用以下功能使用 fieldId 列表动态形成查询。
public List<CompareDesignGroup> GroupFields(List<string> fieldIdList)
{
StringBuilder sb = new StringBuilder();
foreach (string fieldId in fieldIdList)
{
sb.Append("'" + fieldId + "',");
}
string fieldList = sb.ToString().TrimEnd(',');
string queryString = "";
int i = 0;
foreach(string fieldId in fieldIdList)
{
queryString = queryString + " Select FieldID , CDGroups.Name,
CDCaption, IIF(ISNULL(Priority),99,Priority), " + i + " from Fields LEFT OUTER
JOIN CDGroups ON Fields.CDGroupID = CDGroups.CDGroupID
WHERE Fields.FieldID = '" + fieldId + "' ";
if (i < fieldIdList.Count - 1)
{
queryString = queryString + " union ";
}
i++;
}
queryString = queryString + " order by 4,5 ";
//DatReader 阅读部分...
dataReader = settingsData.ReadSettingsData(queryString);
if (!dataReader.HasRows)
{
return null;
}
List<CompareDesignGroup> compareDesignGroupList = new List<CompareDesignGroup>();
while (dataReader.Read())
{
CompareDesignGroup compareDesignGroup = new CompareDesignGroup();
compareDesignGroup.CdGroup = dataReader["Name"].ToString();
compareDesignGroup.FieldId = dataReader["FieldID"].ToString();
compareDesignGroup.CdCaption = dataReader["CDCaption"].ToString();
compareDesignGroupList.Add(compareDesignGroup);
}
return compareDesignGroupList;
}
当我使用大量字段元素执行上述查询时,MS Access 会引发异常,因为查询太复杂并且应用程序停止执行。有没有更好的方法来写上面的查询?或者有什么办法可以避免这个异常?