SQL Server
SQL Server
Compress and Decompress a String
See more Compression Examples
Demonstrates how to compress and decompress a string.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 assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
DECLARE @sb int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sb OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
DECLARE @i int
SELECT @i = 1
WHILE @i <= 20
BEGIN
EXEC sp_OAMethod @sb, 'Append', @success OUT, 'This is the original uncompressed string.' + CHAR(13) + CHAR(10)
SELECT @i = @i + 1
END
DECLARE @compress int
EXEC @hr = sp_OACreate 'Chilkat.Compression', @compress OUT
EXEC sp_OASetProperty @compress, 'Algorithm', 'deflate'
-- Indicate that the utf-8 byte representation of the string should be compressed.
EXEC sp_OASetProperty @compress, 'Charset', 'utf-8'
EXEC sp_OAMethod @sb, 'GetAsString', @sTmp0 OUT
EXEC sp_OAMethod @compress, 'CompressString', @compressedBytes OUT, @sTmp0
-- If the compressed data is desired in string format, then get the base64 representation of the bytes.
EXEC sp_OASetProperty @compress, 'EncodingMode', 'base64'
DECLARE @compressedBase64 nvarchar(4000)
EXEC sp_OAMethod @sb, 'GetAsString', @sTmp0 OUT
EXEC sp_OAMethod @compress, 'CompressStringENC', @compressedBase64 OUT, @sTmp0
PRINT 'Compressed Bytes as Base64: ' + @compressedBase64
-- Now decompress...
DECLARE @decompressedString nvarchar(4000)
EXEC sp_OAMethod @compress, 'DecompressString', @decompressedString OUT, @compressedBytes
PRINT 'The original string after decompressing from binary compressed data:'
PRINT @decompressedString
-- To decompress from Base64...
EXEC sp_OASetProperty @compress, 'EncodingMode', 'base64'
EXEC sp_OAMethod @compress, 'DecompressStringENC', @decompressedString OUT, @compressedBase64
PRINT 'The original string after decompressing from Base64:'
PRINT @decompressedString
EXEC @hr = sp_OADestroy @sb
EXEC @hr = sp_OADestroy @compress
END
GO