Tuesday, September 15, 2009

SharePoint Batch Delete

It would be inefficient to delete many List items one by one when the List is huge. SharePoint provides a batch update mechanism using CAML. Following code snippet illustrates such usage where all records in a SharePoint List that have not been updated for more than 1 year will be deleted:
    void DeleteOldListItems(SPSite site, string webUrl, string listName)
    {
        StringBuilder sbDelete = new StringBuilder();
        sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
        // CAML query for batch deleting
        string batchDeleteCaml = 
"<Method><SetList Scope=\"Request\">{0}</SetList><SetVar Name=\"ID\">{1}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>"; // Query items not touched for more than a year; same as <Value Type="DateTime"><Today OffsetDays="-365" /></Value> string filterQueryCaml = @"<Where><Geq><FieldRef Name='Modified'/><Value Type='DateTime' IncludeTimeValue='TRUE'>" + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddYears(-1)) + "</Value></Geq></Where>"; using (SPWeb web = site.OpenWeb(webUrl)) { SPList list = web.Lists[listName]; SPQuery filterQuery = new SPQuery(); filterQuery.Query = filterQueryCaml; SPListItemCollection filterItems = list.GetItems(filterQuery); foreach (SPListItem item in filterItems) { sbDelete.Append(string.Format(batchDeleteCaml, list.ID.ToString(), item.ID.ToString())); } sbDelete.Append("</Batch>"); web.ProcessBatchData(sbDelete.ToString()); } }