如何将 TVP 中的缓冲区数据从 node.js 传递到 lambda 中的 sql 服务器?

How to pass buffer data in TVP from node.js to sql server in lambda?

我有一个 lambda 函数,可以通过存储过程在 sql 服务器中保存多条记录。我将来自 lambda 的数据作为 table 值参数 (TVP) 传递。

我能够在 TVP 中成功发送 2 列 varchar 类型,但我需要传递第 3 列,其中包含要保存在 sql 服务器 table 中的文档的缓冲区数据(列类型为图像)。

documentList中的数据如下

 [ 'abc', 'SIGNED', <Buffer 25 50 44 46 ... > ]

当我 运行 代码时,我在控制台中收到错误消息,因为 "RequestError: The data for table-valued parameter "@documents" 不符合参数的 table 类型。SQL 服务器错误是:8029,状态:2"

let list = []
    for (let i = 0; i < documentList.length; i++) {
        list.push({
            "id": documentList[i].id,
            "status": documentList[i].status,
            "fileContent": documentList[i].fileContent
        });
    }
    if (list.length > 0) {
        var rowList = []; 
        for (var i = 0; i < list.length; i++) {
            var paramList = []
            Object.keys(list[i]).forEach(key => {
                paramList.push(list[i][key]);
            });
            rowList.push(paramList);
        }
        var table = {
            columns: [
                { name: "id", type: TYPES.VarChar, length: 200 },
                { name: "status", type: TYPES.VarChar, length: 50 },
                { name: "fileContent", type: TYPES.Image }
            ],
            rows: rowList
        };
        var request = new Request(spUpdateDocumentStatus,
            function (err) {
                if (err) {
                    console.log(err);
                }
               connection.close();
            });
        request.addParameter('documents', TYPES.TVP, table);
        connection.callProcedure(request);
    }

执行时变量"table"中的数据如下

{ columns:
   [ { name: 'id', type: [Object], length: 200 },
     { name: 'status', type: [Object], length: 50 },
     { name: 'fileContent', type: [Object] } ],
  rows:
   [ [ 'abc',
       'SIGNED',
       <Buffer 25 50 44 46 ... > ] ] }

Table 我在 sql 服务器中创建的类型如下

CREATE TYPE [dbo].[TestDocuments] AS TABLE(
    [id] [varchar] (200),
    [status] [varchar] (50),
    [fileContent] [image]
)

正在调用的存储过程如下

CREATE PROCEDURE [dbo].[spUpdateDocumentStatus] @documents TestDocuments readonly
AS
BEGIN
    -- logic
END

注意:在不使用 TVP 的情况下,如果我将与上面相同的缓冲区数据作为 Image 类型传递给存储过程(修改 SP 以接受 Image 数据类型),则代码有效。

尝试使用 varBinary(max) 而不是 Image,它应该没问题。

 var table = {
            columns: [
                { name: "id", type: TYPES.VarChar, length: 200 },
                { name: "status", type: TYPES.VarChar, length: 50 },
                { name: "fileContent", type: TYPES.VarBinary}
            ],
            rows: rowList
        };

并将 table 类型更改为

CREATE TYPE [dbo].[TestDocuments] AS TABLE(
    [id] [varchar] (200),
    [status] [varchar] (50),
    [fileContent] [varBinary](max)
)