简体   繁体   中英

node mssql update query, get rowcount

I'm using the NodeJS package MSSQL ( https://npmjs.org/package/mssql#cfg-node-tds ) to connect to a MS SQL database and perform UPDATE queries.

I understand that if an UPDATE query ends up not affecting any rows, it will still return as a success event. I would like to handle the success event differently if zero rows were affected since this is not the intended outcome of the query.

After doing some research, I found that when performing SQL queries, you can use @@ROWCOUNT to get the number of affected rows, but I've yet to figure out how to use this with the MSSQL Node package.

Has anyone used this Node package and and handled UPDATE queries the way I am trying to?

Thanks!

Okay, right from the link your provided, the node package can call stored procedures.

Either create the logic on the JS side or the TSQL side.

Since I am a DBA/Developer by trade, lets create a SP to perform the update an return the number of rows effected.

I am using the adventure works sample database.

-- use sample db
use AdventureWorks2012;
go

-- sample select
select * 
from [Person].[Person]
where lastname = 'Walters';
go

-- stored procedure
create procedure usp_Update_First_Name (@id int, @first varchar(50))
as
begin
    update [Person].[Person]
    set [FirstName] = @first
    where [BusinessEntityID] = @id;
    return(@@rowcount);
end
go

-- make a call
declare @ret int;
exec @ret = usp_Update_First_Name @id = 4, @first = 'Robert';
print @ret;

This call returns the following output.

(1 row(s) affected) 1

In the JS code, do action A if @ret = 0 or action B if @ret > 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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