Sample code for 30+ languages & platforms
SQL Server

Compress a File to Gzip with Custom Metadata

See more Gzip Examples

This example demonstrates how to use the CompressFile method to create a Gzip (.gz) file while customizing the metadata embedded in the Gzip header.

Before compression, several properties are set:

  • Comment: Adds a descriptive comment to the Gzip file.
  • Filename: Specifies the filename to embed in the Gzip data, which may be used by extraction tools as the default output name.
  • CompressionLevel: Controls the tradeoff between compression ratio and speed (set to maximum in this example).
  • LastModStr: Sets the last-modified timestamp using an RFC 822 formatted date string.

After setting these properties, the input file is compressed and written to a .gz file. This approach allows you to embed meaningful metadata along with the compressed data.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    -- This example demonstrates how to compress a file to Gzip format
    -- while setting custom metadata such as comment, filename,
    -- compression level, and last-modified date.

    DECLARE @gzip int
    EXEC @hr = sp_OACreate 'Chilkat.Gzip', @gzip OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    -- Set custom Gzip properties:
    EXEC sp_OASetProperty @gzip, 'Comment', 'Example Gzip file created with Chilkat'
    EXEC sp_OASetProperty @gzip, 'Filename', 'custom_name.txt'
    EXEC sp_OASetProperty @gzip, 'CompressionLevel', 9
    EXEC sp_OASetProperty @gzip, 'LastModStr', 'Wed, 1 Apr 2025 12:45:26 -0500'

    -- The file to be compressed:
    DECLARE @inputFile nvarchar(4000)
    SELECT @inputFile = 'example.txt'
    DECLARE @outputFile nvarchar(4000)
    SELECT @outputFile = 'example.txt.gz'

    -- Compress the file:
    EXEC sp_OAMethod @gzip, 'CompressFile', @success OUT, @inputFile, @outputFile
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @gzip, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @gzip
        RETURN
      END


    PRINT 'Compression successful.'

    PRINT 'Gzip file created: ' + @outputFile

    EXEC @hr = sp_OADestroy @gzip


END
GO