Sample code for 30+ languages & platforms
SQL Server

Uncompress a Gzip File to a String

See more Gzip Examples

This example demonstrates how to use the UncompressFileToString method to decompress a Gzip (.gz) file that contains text and return the result as a string.

The method reads the compressed file, decompresses the data, and then converts the resulting bytes into a string using the specified character set (in this case, UTF-8).

It is important to specify the correct character set that matches the original encoding of the text. If the wrong character set is used, the resulting string may contain incorrect or unreadable characters.

This method is convenient when working with compressed text data that needs to be processed directly in memory without writing to a file.

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
    DECLARE @iTmp0 int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    -- This example demonstrates how to uncompress a Gzip (.gz) file
    -- that contains text and return the result as a string.

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

    -- The Gzip file to be uncompressed:
    DECLARE @gzPath nvarchar(4000)
    SELECT @gzPath = 'example.txt.gz'

    -- Uncompress the file and interpret the result as UTF-8 text:
    DECLARE @text nvarchar(4000)
    EXEC sp_OAMethod @gzip, 'UncompressFileToString', @text OUT, @gzPath, 'utf-8'
    EXEC sp_OAGetProperty @gzip, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 = 0
      BEGIN
        EXEC sp_OAGetProperty @gzip, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @gzip
        RETURN
      END


    PRINT 'Uncompressed text:'

    PRINT @text

    EXEC @hr = sp_OADestroy @gzip


END
GO