Thursday, December 22, 2011

SharePoint Batch Deleting List Items Programatically

While working on a custom SharePoint solution, I had a requirement to delete multiple list items one time rather than deleting one by one.
Example: Delete only the items from a list which doesn't have value for a custom column.

When i think of the solution i couldn't make new SPListItemCollection object out of the items which needs to be deleted, which is possible in regular c# application development.
However in SharePoint we can do the batch delete of list items using CAML script.
The CAML script needs to be generated for the items which needs to be deleted 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
"{2}" + //{2}-List ItemID
"Delete" +

// Build the CAML delete 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);

//batch delete script.
string batchDeleteScript = string.Format(batchFormat, methodBuilder.ToString());
Execute CAML Script:
Similarly batch updating script can also be generated. Look at the detailed post here for code.

No comments:

Post a Comment