SQL Server
SQL Server
Eval JavaScript Returning Int
See more JavaScript Examples
Demonstrates getting the completion value of a JavaScript that returns an integer.Chilkat SQL Server Downloads
--
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 an integer.
-- 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_int.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 an int.
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
EXEC sp_OASetProperty @result, 'EmitCompact', 0
EXEC sp_OAMethod @result, 'Emit', @sTmp0 OUT
PRINT @sTmp0
-- Output:
-- {
-- "type": "int",
-- "value": 42
-- }
EXEC @hr = sp_OADestroy @sbScript
EXEC @hr = sp_OADestroy @js
EXEC @hr = sp_OADestroy @result
END
GO
JavaScript
const base = 10;
const multiplier = 4;
const offset = 2;
// The last line is a calculation resulting in an integer
// Returns 42.
(base * multiplier) + offset;