SQL Server
SQL Server
Compress a String and Save as a Gzip File
See more Gzip Examples
This example demonstrates how to use the CompressStringToFile method to compress a string and write the result directly to a Gzip (.gz) file.
The input string is first converted to its byte representation using the specified character set (in this case, UTF-8). The resulting bytes are then compressed using the Gzip format, and the compressed output is written directly to the specified file.
This method is convenient when you want to generate a compressed file from in-memory text without needing intermediate objects such as BinData or StringBuilder.
Chilkat SQL Server Downloads
-- 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 string and save the result
-- directly to a Gzip (.gz) file.
DECLARE @gzip int
EXEC @hr = sp_OACreate 'Chilkat.Gzip', @gzip OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
-- The string to be compressed:
DECLARE @inputStr nvarchar(4000)
SELECT @inputStr = 'The quick brown fox jumps over the lazy dog.'
-- Compress the string using UTF-8 and write to a file:
EXEC sp_OAMethod @gzip, 'CompressStringToFile', @success OUT, @inputStr, 'utf-8', 'output.gz'
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 written to output.gz'
EXEC @hr = sp_OADestroy @gzip
END
GO