Fabio Carello
Fabio Carello

Reputation: 1102

Azure Table Storage SDK - Empty a table

This may seem a trivial question, but I'm having some hard time to figure it out. I just need to empty an Azure Storage Table using the .NET SDK.

The only thing I found is the following:

TableOperation deleteOperation = TableOperation.Delete(entity);
TableResult result = await table.ExecuteAsync(entity);

This would require to query the whole table and iterate over the results, which in terms of performance is unreasonable. Is there some method to empty the whole table?

Thanks

Upvotes: 1

Views: 931

Answers (3)

Fabio Carello
Fabio Carello

Reputation: 1102

It seems that DeleteTableIfExists method on CloudTableClient has been discontinuated and moved into Microsoft.WindowsAzure.Storage.Table.CloudTable.

I wrote an extension method EnsureTableIsEmpty which deletes and recreates the table using Polly to provide a basic retry strategy. Below the code:

public static async Task<CloudTable> EnsureTableIsEmpty(this CloudTable table)
{
    await table.DeleteIfExistsAsync();
    await Policy
        .Handle<StorageException>((exc) => { return exc.Message == "Conflict"; })
        .WaitAndRetryAsync(
            5,
            retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
            (exception, timeSpan, retryCount, context) =>
            {
                //Logging stuff
            })
        .ExecuteAsync(() => table.CreateIfNotExistsAsync());

    return table;
}

It is working kinda well. Any suggestion or improv would be nice.

Upvotes: 1

Simon
Simon

Reputation: 1703

You can delete an entire table like so:

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
tableClient.DeleteTableIfExist("mytable");

As Gaurav points out this is done asynchronously so if you want to recreate the table you will need to use a while loop and keep trying every say 5s until the create works.

Upvotes: 1

Gaurav Mantri
Gaurav Mantri

Reputation: 136369

You can delete the table and recreate it. However please keep in mind that deleting a table is an asynchronous operation on the storage side and may take at least 30 seconds or more (depending on the data). While a table is being deleted, you can’t recreate it.

Other alternative is to make use of Entity Batch transactions and delete 100 entities at a time. This will be faster than deleting single entities.

Upvotes: 1

Related Questions