Thursday, December 22, 2011

SharePoint Batch Updating List Items Programatically

While working on a custom SharePoint solution, I had a requirement to update multiple list items one time rather than updating one by one.
Example: Update only the items in a list which doesn't have value for a custom column (update with some value).

When i think of the solution i couldn't make new SPListItemCollection object out of the items which needs to be updated, which is possible in regular c# application development.
However in SharePoint we can do the batch update of list items using CAML script.
The CAML script needs to be generated for the items which needs to be updated as below.

Get the list items:
SPListItemCollection items = spList.Items;
Generate CAML Script:
StringBuilder methodBuilder = new StringBuilder();

string batchFormat = "" +
"{0}"; //{0}-methodFormat

string methodFormat = "" + //{0}-Unique Value for each Item
"{1}" + //{1}-List Guid
"Save" +
"{2}" + //{2}-List ItemID
"{4}" + //{3}-Column Name, {4}-Column Value
"";

// Build the CAML update command script.
foreach (SPListItem item in items)
{
    //get the custom column value
    string customColumnValue = string.Empty;
    if (null != item["CustomColumnName"])
        customColumnValue = item["CustomColumnName"].ToString();
    
    //check whether custom column is empty
    if (string.IsNullOrEmpty(customColumnValue))
    {
        methodBuilder.AppendFormat(methodFormat, item.ID, item.ParentList.ID, item.ID, "CustomColumnName", "New Updated Value");
    }
}

//batch update script.  
string batchUpdateScript = string.Format(batchFormat, methodBuilder.ToString());
Execute CAML Script:
spWeb.ProcessBatchData(batchUpdateScript);

Similarly batch deleting script can also be generated. Look at the detailed post here for code.

7 comments:

  1. when I try to use this code I am getting an error as:
    0x80070057

    ReplyDelete
    Replies
    1. Make sure you have given the internal column name...

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Hi,
    ProcessBatchData not working for me, I don't see my date updated.

    ReplyDelete
  4. Excellent Blog! Thanks for the help!

    ReplyDelete
  5. Can you post the Powershell version of this for SP 2013?

    ReplyDelete