SQL Server
SQL Server
Compress String Feed to Base64
See more Compression Examples
This example receives incoming text data in chunks, compresses as a stream, and accumulates the compressed data in base64.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 @sbCompressedBase64 int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbCompressedBase64 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'
EXEC sp_OASetProperty @compress, 'EncodingMode', 'base64'
EXEC sp_OASetProperty @compress, 'FirstChunk', 1
EXEC sp_OASetProperty @compress, 'LastChunk', 0
DECLARE @bdCompressed int
EXEC @hr = sp_OACreate 'Chilkat.BinData', @bdCompressed OUT
DECLARE @sbUncompressedChunk int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbUncompressedChunk OUT
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
PRINT 'The base64 encoded compressed text:'
EXEC sp_OAMethod @bdCompressed, 'GetEncoded', @sTmp0 OUT, 'base64'
PRINT @sTmp0
-- Decompress in one call:
DECLARE @originalText nvarchar(4000)
EXEC sp_OAMethod @bdCompressed, 'GetEncoded', @sTmp0 OUT, 'base64'
EXEC sp_OAMethod @compress, 'DecompressStringENC', @originalText OUT, @sTmp0
PRINT @originalText
EXEC @hr = sp_OADestroy @sbCompressedBase64
EXEC @hr = sp_OADestroy @compress
EXEC @hr = sp_OADestroy @bdCompressed
EXEC @hr = sp_OADestroy @sbUncompressedChunk
END
GO