Listing 2: The Decompression Function using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.IO; using System.IO.Compression; public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true, DataAccess = DataAccessKind.None)] public static SqlBytes fn_decompress(SqlBytes compressedBlob) { if (compressedBlob.IsNull) return compressedBlob; // Prepare to read the data from the compressed stream. DeflateStream decompressor = new DeflateStream(compressedBlob.Stream, CompressionMode.Decompress, true); // BEGIN CALLOUT A // Initialize the variables. int bytesRead = 1; int chunkSize = 10000; byte[] chunk = new byte[chunkSize]; // Prepare the destination stream to hold the decompressed data. MemoryStream decompressedData = new MemoryStream(); try { // Read from the compressed stream. while ((bytesRead = decompressor.Read(chunk, 0, chunkSize)) > 0) { // Write the decompressed data. decompressedData.Write(chunk, 0, bytesRead); } } // END CALLOUT A catch (Exception) { throw; } finally { // Clean up. decompressor.Close(); decompressor = null; } // Return a decompressed BLOB. return new SqlBytes(decompressedData); } };