In Windows SharePoint Services 3.0, sometimes you must update multiple items in a list. Creating a foreach loop to iterate through a list item collection and performing an Update
on each list item can be very intensive. An alternative approach is to
construct a Collaborative Application Markup Language (CAML) string that
contains a batch of commands to perform the updates and execute the
commands by using the ProcessBatchData command of an SPWeb
object. This Microsoft Office Visual How To demonstrates how to
construct and execute a batch of commands to update text and date fields
for all items in a list.
// Set up the variables to be used.
StringBuilder methodBuilder = new StringBuilder();
string batch = string.Empty;
DateTime currentDate = DateTime.Now;
string formattedDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(currentDate);
string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ows:Batch OnError=\"Return\">{0}</ows:Batch>";
string methodFormat = "<Method ID=\"{0}\">" +
"<SetList>{1}</SetList>" +
"<SetVar Name=\"Cmd\">Save</SetVar>" +
"<SetVar Name=\"ID\">{2}</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#Processed\">{3}</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#Processed_x0020_Date\">{4}</SetVar>" +
"</Method>";
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
// Get the list containing the items to update.
SPList list = web.Lists["Processed Documents"];
string listGuid = list.ID.ToString();
// Query to get the unprocessed items.
SPQuery query = new SPQuery();
query.Query = "<Where><Neq><FieldRef Name='Processed'/>
<Value Type='Choice'>1</Value></Neq></Where>";
query.ViewAttributes = "Scope='Recursive'";
SPListItemCollection unprocessedItems = list.GetItems(query);
// Build the CAML update commands.
for (int i = 0; i < unprocessedItems.Count; i++)
{
int itemID = unprocessedItems[i].ID;
methodBuilder.AppendFormat(methodFormat, itemID, listGuid, itemID, 1, formattedDate);
}
// Put the pieces together.
batch = string.Format(batchFormat, methodBuilder.ToString());
// Process the batch of commands.
string batchReturn = web.ProcessBatchData(batch);
}
}
}
No comments:
Post a Comment
Thank you for Commenting Will reply soon ......