简体   繁体   English

node-mssql 事务插入 - 返回插入的 id..?

[英]node-mssql Transaction insert - Returning the inserted id..?

I'm using node-mssql 3.2.0 and I need to INSERT INTO a table and return the id of the inserted record.我正在使用node-mssql 3.2.0,我需要INSERT INTO一个表并返回插入记录的 ID。

I can successfully use sql.Transaction() to insert data, but the only parameters given to callbacks ( request.query() and transaction.commit() ) are:我可以成功地使用sql.Transaction()来插入数据,但是给回调( request.query()transaction.commit() )的唯一参数是:

const request = new sql.Request();
request.query('...', (err, recordset, affected) => {});

const transaction = new sql.Transaction();
transaction.commit((err) => {});

So recordset is undefined for INSERT , UPDATE and DELETE statements, and affected is the number of rows affected, in my case 1 .因此recordset对于INSERTUPDATEDELETE语句是undefined的, affected的是受影响的行数,在我的例子中是1

Does anyone know a good way to obtain an inserted records id (just a primary key id) after a transaction.commit() using node-mssql ..?有谁知道在使用node-mssqltransaction.commit()之后获取插入记录 id(只是主键 id)的好方法 ..?

Instead of just doing an INSERT INTO... statement, you can add a SELECT... statement as well: 您可以添加SELECT...语句,而不仅仅是执行INSERT INTO...语句:

INSERT INTO table (...) VALUES (...); SELECT SCOPE_IDENTITY() AS id;

The SCOPE_IDENTITY() function returns the inserted identity column, which means recordset now contains the id : SCOPE_IDENTITY()函数返回插入的标识列,这意味着recordset现在包含id

const request = new sql.Request();
request.query('...', (err, recordset, affected) => {});

I don't think request.multiple = true; 我不认为request.multiple = true; is required, because although this includes multiple statements, only one of them is a SELECT... and so returns. 是必需的,因为虽然这包括多个语句,但只有其中一个是SELECT...所以返回。

So the answer was SQL related and is not specific to node-mssql . 所以答案是SQL相关的,并不是node-mssql特有的。

I know this question has accepted answer.我知道这个问题已经接受了答案。 I made the following way:我做了以下方式:

    let pool = await sql.connect(config);
    let insertItem = await pool.request()
    .input('ItemId',sql.NVarChar, 'itemId1234')
    .input('ItemDesc',sql.NVarChar, 'nice item')
    .query("insert into itemTable (Id, ItemId,ItemDesc) OUTPUT INSERTED.ID 
    values (NEWID(), @ItemId, @ItemDesc);
    var insertedItemId = insertItem.recordset[0].ID

This adds unique identifier to data that is saved to db (if table is created so)这会为保存到数据库的数据添加唯一标识符(如果表是这样创建的)

create table itemTable(

       Id UNIQUEIDENTIFIER primary key default NEWID(),
       ItemId nvarchar(25),
       ItemDesc nvarchar(25)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM