Sample code for 30+ languages & platforms
SQL Server

Eval JavaScript Returning String

See more JavaScript Examples

Demonstrates getting the completion value of a JavaScript that returns a string.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    --  This example demonstrates getting the completion value of a script,
    --  where the last evaluated expression is a string.

    --  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, 'js_eval_return_string.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
    --  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 a string.
    EXEC sp_OAMethod @js, 'Eval', @success OUT, @sbScript, @result
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @js, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @sbScript
        EXEC @hr = sp_OADestroy @js
        EXEC @hr = sp_OADestroy @result
        RETURN
      END

    EXEC sp_OASetProperty @result, 'EmitCompact', 0
    EXEC sp_OAMethod @result, 'Emit', @sTmp0 OUT
    PRINT @sTmp0

    --  Output:

    --  {
    --    "type": "string",
    --    "value": "Ready for Chilkat.Js"
    --  }

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


END
GO
JavaScript
var status = "Ready";
var system = "Chilkat.Js";

// The last statement is an expression
status + " for " + system;