SQL Server
SQL Server
Compress Text Feed to Binary
See more Compression Examples
This example receives incoming text data in chunks, compresses as a stream, and accumulates the compressed binary data.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 @bdCompressed int
EXEC @hr = sp_OACreate 'Chilkat.BinData', @bdCompressed OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
DECLARE @compress int
EXEC @hr = sp_OACreate 'Chilkat.Compression', @compress OUT
EXEC sp_OASetProperty @compress, 'Algorithm', 'deflate'
EXEC sp_OASetProperty @compress, 'Charset', 'utf-8'
DECLARE @sbUncompressedChunk int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbUncompressedChunk OUT
EXEC sp_OASetProperty @compress, 'FirstChunk', 1
EXEC sp_OASetProperty @compress, 'LastChunk', 0
DECLARE @i int
SELECT @i = 0
WHILE @i <= 24
BEGIN
IF @i = 24
BEGIN
EXEC sp_OASetProperty @compress, 'LastChunk', 1
END
EXEC sp_OAMethod @sbUncompressedChunk, 'Clear', NULL
EXEC sp_OAMethod @sbUncompressedChunk, 'AppendInt', @success OUT, @i
EXEC sp_OAMethod @sbUncompressedChunk, 'Append', @success OUT, ': This is a line of data to be compressed...' + CHAR(13) + CHAR(10)
EXEC sp_OAMethod @compress, 'CompressSb', @success OUT, @sbUncompressedChunk, @bdCompressed
EXEC sp_OASetProperty @compress, 'FirstChunk', 0
SELECT @i = @i + 1
END
-- Show the compressed data in hex format:
PRINT 'The hex encoded compressed text:'
EXEC sp_OAMethod @bdCompressed, 'GetEncoded', @sTmp0 OUT, 'hex'
PRINT @sTmp0
-- Now decompress in one call. It is important to set both FirstChunk and LastChunk = 1
DECLARE @bdDecompressed int
EXEC @hr = sp_OACreate 'Chilkat.BinData', @bdDecompressed OUT
EXEC sp_OASetProperty @compress, 'FirstChunk', 1
EXEC sp_OASetProperty @compress, 'LastChunk', 1
EXEC sp_OAMethod @compress, 'DecompressBd2', @success OUT, @bdCompressed, @bdDecompressed
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @compress, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @bdCompressed
EXEC @hr = sp_OADestroy @compress
EXEC @hr = sp_OADestroy @sbUncompressedChunk
EXEC @hr = sp_OADestroy @bdDecompressed
RETURN
END
DECLARE @originalText nvarchar(4000)
EXEC sp_OAMethod @bdDecompressed, 'GetString', @originalText OUT, 'utf-8'
PRINT @originalText
EXEC @hr = sp_OADestroy @bdCompressed
EXEC @hr = sp_OADestroy @compress
EXEC @hr = sp_OADestroy @sbUncompressedChunk
EXEC @hr = sp_OADestroy @bdDecompressed
END
GO