Sample code for 30+ languages & platforms
SQL Server

Implement Preprocessor #include with StringBuilder

Demonstrates how to implement #include with a Chilkat StringBuilder.

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)
    -- First build a string that has a preprocessor include
    DECLARE @sbSrc int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbSrc OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    DECLARE @success int
    EXEC sp_OAMethod @sbSrc, 'Append', @success OUT, '1' + CHAR(13) + CHAR(10) + '2' + CHAR(13) + CHAR(10) + '3' + CHAR(13) + CHAR(10)
    EXEC sp_OAMethod @sbSrc, 'Append', @success OUT, '#include <qa_data/txt/helloWorld.txt>' + CHAR(13) + CHAR(10)
    EXEC sp_OAMethod @sbSrc, 'Append', @success OUT, '4' + CHAR(13) + CHAR(10) + '5' + CHAR(13) + CHAR(10)

    EXEC sp_OAMethod @sbSrc, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    -- sbSrc contains:
    -- 	1
    -- 	2
    -- 	3
    -- 	#include <qa_data/txt/helloWorld.txt>
    -- 	4
    -- 	5

    -- The qa_data/txt/helloWorld.txt file contains "Hello World!"

    DECLARE @filePath nvarchar(4000)
    EXEC sp_OAMethod @sbSrc, 'GetAfterBetween', @filePath OUT, '#include', '<', '>'
    EXEC sp_OAGetProperty @sbSrc, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 <> 1
      BEGIN

        PRINT 'No #include''s found.'
        EXEC @hr = sp_OADestroy @sbSrc
        RETURN
      END


    PRINT 'filePath: ' + @filePath

    -- Load the contents of the filePath
    DECLARE @sbIncludeFile int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbIncludeFile OUT

    EXEC sp_OAMethod @sbIncludeFile, 'LoadFile', @success OUT, @filePath, 'utf-8'

    -- Replace the first occurrence of #include <...> line with the contents of the include file.
    EXEC sp_OAMethod @sbIncludeFile, 'GetAsString', @sTmp0 OUT
    EXEC sp_OAMethod @sbSrc, 'ReplaceAllBetween', @success OUT, '#include', '>', @sTmp0, 1

    EXEC sp_OAMethod @sbSrc, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    -- sbSrce now contains:
    -- 	1
    -- 	2
    -- 	3
    -- 	Hello World!
    -- 	4
    -- 	5

    EXEC @hr = sp_OADestroy @sbSrc
    EXEC @hr = sp_OADestroy @sbIncludeFile


END
GO