Sample code for 30+ languages & platforms
SQL Server

How to Avoid Large Strings in HTTP Responses

See more HTTP Examples

In some programming languages/environments, returning and passing large strings is problematic for both performance and other reasons (for example, with SQL Server limitations on sizes varchar variables).

One way of avoiding the need to return the actual string data, is to pass the data from one place to another via a Chilkat StringBuilder or BinData object. This example demonstrates a simple HTTP GET where the response body contains XML approximately 274K in size. The response body is loaded into the Chilkat.Xml without the XML content ever needing to leave the native code internal to Chilkat.

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)
    DECLARE @success int
    SELECT @success = 0

    -- This example assumes the Chilkat HTTP API to have been previously unlocked.
    -- See Global Unlock Sample for sample code.

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

    DECLARE @resp int
    EXEC @hr = sp_OACreate 'Chilkat.HttpResponse', @resp OUT

    EXEC sp_OAMethod @http, 'HttpNoBody', @success OUT, 'GET', 'https://www.chilkatsoft.com/hamlet.xml', @resp
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @http, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @resp
        RETURN
      END

    DECLARE @sb int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sb OUT

    -- Copy the response body to sb.
    EXEC sp_OAMethod @resp, 'GetBodySb', @success OUT, @sb

    DECLARE @xml int
    EXEC @hr = sp_OACreate 'Chilkat.Xml', @xml OUT

    -- Load the XML from the sb.
    DECLARE @bAutoTrim int
    SELECT @bAutoTrim = 0
    EXEC sp_OAMethod @xml, 'LoadSb', @success OUT, @sb, @bAutoTrim


    EXEC sp_OAGetProperty @sb, 'Length', @iTmp0 OUT

    PRINT 'The response body was ' + @iTmp0 + ' characters in length.'

    PRINT 'Success.'

    -- The output is:
    -- 
    -- 	The response body was 279658 characters in length.
    -- 	Success.

    EXEC @hr = sp_OADestroy @http
    EXEC @hr = sp_OADestroy @resp
    EXEC @hr = sp_OADestroy @sb
    EXEC @hr = sp_OADestroy @xml


END
GO