如何使用 nodejs 的 mssql 包调用 SQL 服务器标量函数?

How does one call a SQL Server scalar function using the mssql package for nodejs?

我在 SQL Server 2012 中有一个自定义标量函数。它需要 2 个浮点数和 returns 个 nvarchar。经过测试并在 SQL 服务器内工作。

我没有找到任何有关如何从 node-mssql 调用它的示例。我所做的尝试失败了:

TypeError: Cannot set property 'value' of undefined

这似乎是 node-tedious 包的错误...所以可能 tedious 还不支持它。

我有一个使用两个输入参数调用存储过程的工作版本 returns 一个记录集,但因为我真的只需要一个值,所以它似乎结束了,并且 executeScalar 调用将是在这里很有用(我习惯于从 .NET 获得的东西)。

您可以跳过 node-mssql 中的 input/output 设置,只需像往常一样 select 标量函数。

函数

CREATE FUNCTION [dbo].[udfTestScalar] (
    -- Add the parameters for the function here
    @F1 FLOAT
    ,@F2 FLOAT
    )
RETURNS NVARCHAR(100)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @N1 NVARCHAR(100)

    -- Add the T-SQL statements to compute the return value here
    SET @N1 = N'Hi there'

    RETURN @N1
END

index.js

var sql = require('mssql');

var config = {
    user: 'user',
    password: 'password',
    server: 'localhost',
    database: 'db'
};

var connection = new sql.Connection(config, function(err) {
    var request = new sql.Request(connection);
    request.query("SELECT dbo.udfTestScalar(12345.123, 12345.456) as result", function(err, recordsets) {
        console.log(recordsets[0].result);
    });
});

输出

% node index.js
'Hi there'