How to do bulk deletion in SharePoint?

by Victor 20. April 2010 16:05

How to bulk delete in SharePoint?

The normal way to delete file programmatically in SharePoint is using the SharePoint API. The code looks like:

foreach(SPList myList in myWeb)
{
  foreach( SPListItem item in myList )
  {
    item.Delete();
  }
}

This works fine for document libraries contain small amount of data. It will be extremely slow when you have document libraries contain millions of records. In this case, you will need bulk deletion.

In order to use bulk deletion you need to know the CAML and how to use SPWeb.ProcessBatchData() methods.
There is the example.

private static String BuildBatchDeleteCommand( SPList list, SPListItemCollection coll )
{
  StringBuilder sbDelete = new StringBuilder();
  sbDelete.Append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>" );
 
  // We prepare a String.Format with a String.Format, this is why we have a {{0}}
  string command = String.Format( "<Method><SetList Scope=\"Request\">{0}</SetList><SetVar Name=\"ID\">{{0}}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar><SetVar Name=\"owsfileref\">{{1}}</SetVar></Method>", list.ID );
  foreach ( SPListItem item in coll )
  {
    sbDelete.Append( string.Format( command, item.ID.ToString(), item.File.ServerRelativeUrl ) );
  }
  sbDelete.Append( "</Batch>" );
  return sbDelete.ToString();
}

// While there's something left
while ( list.ItemCount > 0 )
{
  // We get everything but we limit the result to 100 rows
  SPQuery q = new SPQuery();
  q.RowLimit = 100;
 
  // We get the results
  SPListItemCollection coll = list.GetItems( q );
 
  // We process a CAML batch
  String batch = BuildBatchDeleteCommand( list, coll );
 
  // We execute it
  web.ProcessBatchData( batch );
 
  list.Update();
}

BTW the methods returns a String, if your code doesn’t work, it would return you an error code. If everything is fine, it just return "0x00000000".

Tags:

Programming | Sharepoint

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

Month List