Sample code for 30+ languages & platforms
SQL Server

JavaScript console

See more JavaScript Examples

Demonstrates console output using Chilkat JavaScript.

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
    -- 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 demonstrates using the built-in console object.
    -- The Javascript run in this example is shown below.

    -- Load the JavaScript from a file.
    DECLARE @sbScript int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbScript OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @sbScript, 'LoadFile', @success OUT, 'qa_data/js_tests/test_console.js', 'utf-8'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @sbScript, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @sbScript
        RETURN
      END

    DECLARE @js int
    EXEC @hr = sp_OACreate 'Chilkat.Js', @js OUT

    DECLARE @result int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @result OUT

    -- Run the JavaScript
    -- Results (not console output) go to result.
    -- Note: Eval returns the completion value of the script. This is generally the value of the last evaluated expression.
    -- In this case, the last evaluated expression is console.log which does not calculate a value. Therefore, it returns undefined.
    EXEC sp_OAMethod @js, 'Eval', @success OUT, @sbScript, @result
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @sbScript, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @sbScript
        EXEC @hr = sp_OADestroy @js
        EXEC @hr = sp_OADestroy @result
        RETURN
      END

    -- We can look at the result, which is "undefined", which is normal and expected.
    EXEC sp_OAMethod @result, 'Emit', @sTmp0 OUT
    PRINT @sTmp0
    -- The result JSON is: {"type":"undefined","value":"undefined"}

    -- The console output is retrieved by calling ConsoleOutputSb
    DECLARE @sbOut int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbOut OUT

    EXEC sp_OAMethod @js, 'ConsoleOutputSb', NULL, @sbOut
    EXEC sp_OAMethod @sbOut, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    EXEC @hr = sp_OADestroy @sbScript
    EXEC @hr = sp_OADestroy @js
    EXEC @hr = sp_OADestroy @result
    EXEC @hr = sp_OADestroy @sbOut


END
GO